說我有一類像...覆蓋抽象接口財產
public abstract class Base
{
public abstract IAttributes Attributes{ get; set; }
}
public interface IAttributes
{
string GlobalId { get; set; }
}
而且像這樣一類...
public class ImplementAttributes : IAttributes
{
public string GlobalId { get; set; } = "";
public string LocalId { get; set; } = "";
// Other Properties and Methods....
}
然後,我實現它像...
public class Derived: Base
{
public new ImplementAttributes Attributes { get; set; }
}
現在,我意識到上述不會工作,因爲我不能覆蓋屬性屬性,如果我隱藏它新那麼下面的波紋管爲null,因爲基地屬性不被寫入。
public void DoSomethingWithAttributes(Base base)
{
var Foo = FindFoo(base.Attributes.GlobalId); // Null because its hidden
}
但是我想能夠訪問基地和衍生財產最終屬性,如以上。
這能實現呢?有沒有更好的辦法?
如果你想同時訪問,你要麼擁有它(使用'new')隱藏或定義另一個接口,並明確實現它。否則,如果您知道運行時類型是什麼,您總是可以選擇投射。 –
我更新了我的問題。我嘗試新的,我認爲這是最接近我想要實現的,但是當我作爲基地傳遞派生的對象,然後該屬性爲空。 – BrokenRobot
這不回答你的問題? https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-define-abstract-properties –