在C#类中隐含一个泛型类型参数

时间:2018-09-17 13:30:27

标签: c# generics

假设我有一个这样的课程:

public class Demo<A, B>
    where A : IEquatable<A>
    where B : IList<A>, new()
{
    ...
}

创建实例非常简单:

Demo<string, List<string>> test1 = new Demo<string, List<string>>();
// or more concisely:
var test2 = new Demo<string, List<string>>();

我的问题是:创建实例时,是否可以重写类Demo而不显式要求类型A?像这样的东西(显然不起作用):

B

对于我正在从事的特定项目来说,这并不是什么大问题,但是重复创建实例所需的类型参数激起了我的好奇心。

编辑
感谢所有建议,对我来说,它可以更好地说明问题。我想我可以将问题改写为:泛型类可以访问其约束的泛型的泛型类型参数吗?

因此可以按照以下方式创建一些东西:

public class Demo<B>
    where B : IList<A>, new()
        where A : IEquatable<A>
....

var test = new Demo<List<string>>(); // Only one type parameter

...并在我的代码中同时访问public IMyInterface<T> where T : IEquatable<T>... public class myClass<A> where A : IMyInterface<B>, new()... // doesn't compile A?我怀疑不是。

3 个答案:

答案 0 :(得分:2)

您可以定义一个中间接口,该接口将在A和B之间进行类型映射

31

然后定义您的Demo类。

public interface IDemo<A, B> 
    where A : IEquatable<A>
    where B : IList<A>, new()
{

}

然后可以根据需要使用

public class Demo<B> : IDemo<B, List<B>>
    where B : IEquatable<B> // This is required for this type definition
{

}

答案 1 :(得分:0)

在不知道Demo类的实际内容的情况下找出来有点棘手,但是为什么您需要将List视为通用参数?

为什么不简单

public class Demo<A> where A : IEquatable<A>
{
    public Demo()
    {
       DemoB = new List<A>();
    }

    public Demo(A demoA) : this()
    {
        DemoA = demoA;            
    }

    public A DemoA { get; }
    public IList<A> DemoB { get; }
}

答案 2 :(得分:0)

D/BluetoothConnectionServ: ConnectedThread: Starting.
E/BluetoothConnectionServ: write: Error reading Input Stream. socket closed

用法

public class BaseDemo<A, B>
    where A : IEquatable<A>
    where B : IList<A>, new()
{
}

public class Demo<B> : BaseDemo<B, List<B>>
    where B : IEquatable<B> 
{
}

查看此工作fiddle

相关问题