我有一个使用奇怪重复模板模式的代码库,带有一个基类和一个派生类。
在接受基类参数的某个方法中,我想检查我收到的参数是否为派生类型,但我无法强制转换为它。
这是一个说明问题的示例:
class Base<T> where T : Base<T> {
}
class Derived<T> : Base<T>
where T : Derived<T> {
}
class DerivedBanana : Derived<DerivedBanana> {
}
class Program {
static void DoSomething<T>(T t) where T : Base<T> {
// CS0311: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Derived<T>'.
// There is no implicit reference conversion from 'T' to 'Derived<T>'.
var d = t as Derived<T>;
}
static void Main(string[] args) {
DoSomething(new DerivedBanana());
}
}
有什么办法可以在我的 DoSomething
中登记吗?方法如果 T
我得到的参数实际上是一个 Derived<T>
?备注 :我正在重构我的代码以避免这种情况,但我仍然想知道如何进行这样的转换:)
注释 2 :建议的重复项没有回答我的问题:我想知道如何转换为派生类型,而不仅仅是检查变量是否为派生类型。
最佳答案
Is there a way I can check in my DoSomething method if the T parameter I'm getting is actually a Derived?
Derived<T>
类可以用 Base<T>
约束获得更弱的类型安全形式public class Base<T> where T : Base<T>
{
public virtual Base<T> This(){
return this as T;
}
}
public class Derived<T> : Base<T>
where T: Base<T>
{
public override Derived<T> This()
{
return base.This() as Derived<T>;
}
}
class DerivedBanana : Derived<DerivedBanana>
{
}
class BaseBanana : Base<BaseBanana>
{
}
class Program
{
static void DoSomething<T>(T t) where T : Base<T>
{
T d = (T)(t.This() as Derived<T> ?? t.This() as Base<T>);
Console.WriteLine(d.GetType());
}
static void Main(string[] args)
{
DoSomething(new BaseBanana());
DoSomething(new DerivedBanana());
}
}
关于c# - 转换到一个奇怪的重复派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67001809/