在 c# 中有什么方法可以让 Type 包含它自己吗?
Is there any way in c# to have Type which includes itself?
一种编写我想要的代码的方法如下,但我不太喜欢新的隐藏
public class Bar
{
public TReturn Baz<TReturn>()
where TReturn : Bar
{
return this as TReturn;
}
}
public class Foo : Bar
{
public new TReturn Baz<TReturn>()
where TReturn : Foo
{
return base.Baz<TReturn>() as TReturn;
}
}
class Test
{
public void Main()
{
var foo = new Foo();
var foo2 = foo.Baz<Foo>();
Assert.IsInstanceOfType(foo.GetType(), foo2);
}
}
相反,我想知道泛型类型是否可以包含自身?类似于以下内容。
public class Bar<TReturn>
where TReturn : Bar<TReturn>
{
public TReturn Baz()
{
return this as TReturn;
}
}
public class Foo<TReturn> :
Bar<TReturn>
where TReturn : Bar<TReturn>
{
}
class Test
{
public void Main()
{
var foo = new Foo<???>();
var foo2 = foo.Baz();
Assert.IsInstanceOfType(foo.GetType(), foo2);
}
}
你应该看看这个:
Article by Eric Lippert
他在一定程度上解释了这种模式,它是 Curiously recurring template pattern
的变体
感谢 Dog Ears 提供的模式名称和初始提示。
作为参考,我当前的解决方案是清理 Foo,因此它不需要传入的类型。
public class Bar<TReturn>
where TReturn : Bar<TReturn>
{
public TReturn Baz()
{
return this as TReturn;
}
}
public class Foo : Bar<Foo>
{
}
class Test
{
public void Main()
{
var foo = new Foo();
var foo2 = foo.Baz();
Assert.IsInstanceOfType(foo.GetType(), foo2);
}
}
一种编写我想要的代码的方法如下,但我不太喜欢新的隐藏
public class Bar
{
public TReturn Baz<TReturn>()
where TReturn : Bar
{
return this as TReturn;
}
}
public class Foo : Bar
{
public new TReturn Baz<TReturn>()
where TReturn : Foo
{
return base.Baz<TReturn>() as TReturn;
}
}
class Test
{
public void Main()
{
var foo = new Foo();
var foo2 = foo.Baz<Foo>();
Assert.IsInstanceOfType(foo.GetType(), foo2);
}
}
相反,我想知道泛型类型是否可以包含自身?类似于以下内容。
public class Bar<TReturn>
where TReturn : Bar<TReturn>
{
public TReturn Baz()
{
return this as TReturn;
}
}
public class Foo<TReturn> :
Bar<TReturn>
where TReturn : Bar<TReturn>
{
}
class Test
{
public void Main()
{
var foo = new Foo<???>();
var foo2 = foo.Baz();
Assert.IsInstanceOfType(foo.GetType(), foo2);
}
}
你应该看看这个: Article by Eric Lippert 他在一定程度上解释了这种模式,它是 Curiously recurring template pattern
的变体感谢 Dog Ears 提供的模式名称和初始提示。
作为参考,我当前的解决方案是清理 Foo,因此它不需要传入的类型。
public class Bar<TReturn>
where TReturn : Bar<TReturn>
{
public TReturn Baz()
{
return this as TReturn;
}
}
public class Foo : Bar<Foo>
{
}
class Test
{
public void Main()
{
var foo = new Foo();
var foo2 = foo.Baz();
Assert.IsInstanceOfType(foo.GetType(), foo2);
}
}