c#获取父类_.net c#从父类方法返回子类的类型

Solutions1

What you are asking is not strictly polymorphism, since you want to override a return type, and thus have a different signature from the original method. True polymorphism changes none of this signature, so what you're asking isn't a first-class situation in C#.

That being said, there are at least two ways about it.

The simplest way is to override the method, using the new keyword to hide the original method, allowing you to change the signature.

public new B MyMethod() { return (B)(base.MyMethod()); }

This will allow any usages of B to return a B, but does not actually override the behaviour of A.MyMethod. It can be useful to avoid repetitive typecasting in code.

if you need to also override the method to allow it to return an object of type B, this cannot coexist in the same class, because the compiler sees the same signature (same name, same parameters, even though the return type is explcitly different).

The second way is called Static Polymorphism, and is very useful if you're using a factory of some kind, but can bevery tricky to work around, because it allows exactly one level of actual inheritance. A Statically Polymorphic type starts with a type that has a Generic component constrained against itself:

public class A where TSelf : A { }

public class B : A { }

This means your method could return an object of type TSelf or even make this an abstract method so each inheritor has to deal with the constructor, but any class inherited from B has a harder time overriding this, since it's inheriting from A, not A

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值