2017-10-06 60 views
0

說我有一類像...覆蓋抽象接口財產

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 
} 

但是我想能夠訪問基地衍生財產最終屬性,如以上。

這能實現呢?有沒有更好的辦法?

+1

如果你想同時訪問,你要麼擁有它(使用'new')隱藏或定義另一個接口,並明確實現它。否則,如果您知道運行時類型是什麼,您總是可以選擇投射。 –

+0

我更新了我的問題。我嘗試新的,我認爲這是最接近我想要實現的,但是當我作爲基地傳遞派生的對象,然後該屬性爲空。 – BrokenRobot

+0

這不回答你的問題? https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-define-abstract-properties –

回答

2

您可以使用泛型:

public abstract class Base<T> where T: IAttributes 
{ 
    public abstract T Attributes{ get; set; } 
} 

public interface IAttributes 
{ 
    string GlobalId { get; set; } 
} 

而且

public class Derived: Base<ImplementAttributes> 
{ 
    public override ImplementAttributes Attributes { get; set; } 
} 

然後:

public void DoSomethingWithAttributes<T>(Base<T> b) where T : IAttributes 
{ 
    var Foo = FindFoo(b.Attributes.GlobalId); 
} 

你可以通過Derived情況下,不指定類型參數明確:

Derived d = new Derived(); 
DoSomethingWithAttributes(d); 
+0

這是一個很好的答案(+1),我現在對泛型有了更好的理解。但是,它引入了必須傳遞一個類型以及使用Base的問題。我希望能夠簡單地訪問接口屬性,無論知道派生類型。 這可能嗎? – BrokenRobot

+0

可以傳遞到Derived''DoSomethingWithAttributes'的'的實例,而不指定類型參數。類型參數被推斷,因爲「派生」聲明它。 – Blorgbeard

+0

我不認爲你可以避開DoSomethingWithAttributes'的'了更詳細的聲明,雖然。 – Blorgbeard