簡體   English   中英

如何設置基類的派生類屬性

[英]How to set derived class property from base class

首先,讓我說我非常了解這樣做的危險,並理解100%這是一個“壞主意” ...但是...

如何設置基類的派生類屬性?

public class Foo
{
    public void SetSomeValue(int someParam)
    {
        var propertyInfo = this.GetType()
                            .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                            .Where(t => t.Name == "SomeValue")
                            .First();

        propertyInfo.SetValue(null, someParam); // <-- This shouldn't be null
    }
}

public class Bar : Foo
{
    public int SomeValue { get; set; }
}

如何獲得屬性值以調用SetValue?

編輯:

這實際上非常容易。 h

propertyInfo.SetValue(this, someParam);
propertyInfo.SetValue(this, someParam);

用法:

var bar = new Bar {SomeValue = 10};
bar.SetSomeValue(20);
Console.WriteLine(bar.SomeValue); // Should be 20

宣言:

public class Foo
{
    public void SetSomeValue(int someParam)
    {
        var propertyInfo = this.GetType()
            .GetProperties(BindingFlags.Instance | BindingFlags.Public).First(t => t.Name == "SomeValue");

        propertyInfo.SetValue(this, someParam, null);
    }
}

public class Bar : Foo
{
    public int SomeValue
    {
        get;
        set;
    }
}

您可以擺弄接口。 這樣,您至少要耦合到接口而不是實際的派生類。

public class Foo {
    public void SetSomeValue(int someParam) {
        if (this is ISomeValueHolder) {
            ((ISomeValueHolder)this).SomeValue = someParam;
        }
    }
}

public interface ISomeValueHolder {
    int SomeValue { get; set; }
}

public class Bar : Foo, ISomeValueHolder {
    public int SomeValue { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM