开发者

How to get child property inside parent class?

开发者 https://www.devze.com 2023-01-18 06:26 出处:网络
Could you answer me how to do next, please? How to do this with Lambda? Is it possible to delegate some object instance and use its properties and methods in case if this method doesn\'t know type of

Could you answer me how to do next, please? How to do this with Lambda? Is it possible to delegate some object instance and use its properties and methods in case if this method doesn't know type of delegated object?

class class_a {
    public string getChildData<T> (T dynamicInstance) {
        return dynamicInstance.prop;
    }
}

class class_b : a {
    public string prop = "prop_b";
}

class class_c : a {
    public string prop = "prop_c";
}

var inst_b = new b ();
var inst_c = new c ();
b.getChildData(b);
c.getChildData(c开发者_JAVA技巧);

Purpose : to get child property inside parent class?

Update : use Reflection - http://forums.asp.net/t/1608839.aspx

Thanks, Artem


Use an abstract/virtual property instead of a field:

abstract class ClassA
{
    public abstract string MyProperty
    {
        get;
    }

    public void DoIt()
    {
        Console.WriteLine(this.MyProperty);
    }
}

class ClassB : ClassA
{
    public override string MyProperty
    {
        get { return "prop_b"; }
    }
}

class ClassC : ClassA
{
    public override string MyProperty
    {
        get { return "prop_c"; }
    }
}

var instB = new ClassB();
var instC = new ClassC();
instB.DoIt();
instC.DoIt();

See: Inheritance (C# Programming Guide)
See: override (C# Reference)

0

精彩评论

暂无评论...
验证码 换一张
取 消