开发者

Extending abstract classes in c#

开发者 https://www.devze.com 2022-12-29 00:01 出处:网络
I am a Java developer and I have noticed some differences in extending abstract classes in c# as opposed to Java. I was wondering how a c# developer would achived the following.

I am a Java developer and I have noticed some differences in extending abstract classes in c# as opposed to Java. I was wondering how a c# developer would achived the following.

1) Covarience

public abstract class A {
   public abstract List<B> List();
}
public class BList : List<B> {
}
public abstract class C : A { 
   public abstract BList List();
}

So in the above hierarchy, there is covarience in C where it returns a type compatible with what A returns. However this gives me an error in Visual Studio. Is there a way to specify a covarient return 开发者_运维技巧type in c#?

2) Adding a setter to a property

public abstract class A {
   public abstract String Name { get; }
}
public abstract class B : A {
   public abstract String Name { get; set }
}

Here the compiler complains of hiding. Any suggestions?

Please do not suggest using interfaces unless that is the ONLY way to do this.


Somehow I don't understand your Intention. Why don't you solve it like this ?

public class BList : List<T> where T : B {} same =  public class BList : List<B> {}

public class C : A
{
    public override List<B> Liste()
    {
        return new BList();
    }
}

About your second Question :

What you want to do there is bad design in my eyes. You can use the keyword virtual on both and ignore the warnings, but why do you want to do something like this ?

public abstract class A
{
    public virtual string Name { get; protected set; }

}

public abstract class B : A
{
    public virtual string Name { get; set;}
}


Neither of these is supported in C#. Covariant returns are also not supported in the underlying runtime (the CLR).

It appears that it may be possible to do something along the lines of your property example on the CLR, but not in C#. Under the hood, a property essentially consists of a name, the property type, and references to the getter and setter methods (as applicable), which are typically named get_<Property> and set_<Property> (but which are not required to follow that convention in non-CLS-compliant classes). It is possible to create a property in a base class which has only a getter, and then another property in the derived class with the same name and getter, but which has its own setter. However, I don't know that any .NET languages allow such a definition.

0

精彩评论

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

关注公众号