标题可能有些混乱,但是我不确定如何用不同的措词来表达。
我有一个通用类型的类。我希望该类包含相同类的子类,但具有另一个泛型类型。像这样:
public class Test<Foo>
{
private readonly Foo _myFoo;
public Test<ChildFoo> Child { get; set; }
public Test(Foo foo)
{
_myFoo = foo;
}
}
public class Impl
{
public void FooTest()
{
var parent = new Test<string>("tester");
var child = new Test<int>(1234);
parent.Child = child;
}
}
但是我不能有一个带有“ ChildFoo”泛型的孩子。还有其他方法吗?
答案 0 :(得分:4)
尝试一下。
public class Test<T1, T2>
{
private readonly T1 _myFoo;
public T2 Child { get; set; }
public Test(T1 foo)
{
_myFoo = foo;
}
}
public class Impl
{
public void FooTest()
{
var parent = new Test<string, Test<int, object>>("tester");
var child = new Test<int, object>(1234);
parent.Child = child;
}
}
由于第一个解决方案无法满足您的需求,所以我还有一个涉及界面的想法,让您像对待Test<,>
一样对待孩子。
public class Test<T1, T2> : ITest where T2 : ITest
{
private readonly T1 _myFoo;
public T2 Child { get; set; }
public void A()
{
}
public void B()
{
Child.A();
}
public Test(T1 foo)
{
_myFoo = foo;
}
}
public interface ITest
{
void A();
void B();
}
public class Impl
{
public void FooTest()
{
var parent = new Test<string, Test<int, ITest>>("tester");
var child = new Test<int, ITest>(1234);
parent.Child = child;
}
}
答案 1 :(得分:-1)
我会尝试这样的事情:
public class Test<T>
{
private readonly T _myFoo;
public Test(T foo)
{
_myFoo = foo;
}
}
public class ParentTest<T, TChild, TChildType> : Test<T> where TChild : Test<TChildType>
{
TChild Child { get; set; }
}
public class Impl
{
public void FooTest()
{
var parent = new ParentTest<string, Test<int>, int>("tester");
var child = new Test<int>(1234);
parent.Child = child;
}
}
答案 2 :(得分:-1)
这是正确的方法,只需对代码进行最少的修改
public class Test<Foo,ChildFoo>
{
private readonly Foo _myFoo;
public Test<ChildFoo,ChildFoo> Child { get; set; }
public Test(Foo foo)
{
_myFoo = foo;
}
}
public class Impl
{
public void FooTest()
{
var parent = new Test<string,int>("tester");
var child = new Test<int,int>(1234);
parent.Child = child;
}
}