简体   繁体   English

覆盖抽象接口属性

[英]Override abstract interface property

Say I have a class like... 说我有一个像...

public abstract class Base
{
    public abstract IAttributes Attributes{ get; set; }
}

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

And a class like this... 像这样的课

public class ImplementAttributes : IAttributes
{
    public string GlobalId { get; set; } = "";
    public string LocalId { get; set; } = "";
    // Other Properties and Methods....
}

And then I implement it like... 然后我像实施...

public class Derived: Base
{
    public new ImplementAttributes Attributes { get; set; } 
}

Now, I realise the above will not work because I can't override the property Attributes and if I hide it with new then the following bellow is null because the Base property does not get written. 现在,我意识到上面的内容将无法正常工作,因为我无法覆盖属性Attributes,并且如果使用new将其隐藏,则以下波纹管将为null,因为不会写入Base属性。

public void DoSomethingWithAttributes(Base base)
{
    var Foo = FindFoo(base.Attributes.GlobalId);  // Null because its hidden
}

But I would like to be able to access the Base and Derived property attributes eventually like Above. 但我希望能够像上图一样最终访问BaseDerived属性。

Can this be accomplished? 能做到吗? Is there a better way? 有没有更好的办法?

You can use generics: 您可以使用泛型:

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

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

And

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

And then: 接着:

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

You can pass Derived instances without specifying a type parameter explicitly: 您可以传递Derived实例,而无需显式指定类型参数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM