且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#泛型的变量声明,这可能吗?

更新时间:2022-12-24 14:52:20

如果你想使一个字段或属性的类型的 MyClass的通用基于某些类型参数 U ,您必须声明,作为一个类型参数 MyClass的

 公共类MyClass的< T,U> 
,其中T:类
,其中U:类
{
私人MyOtherClass< T,U>变量;
...的内容...
}
公共类MyOtherClass< T,U>
,其中T:类
,其中U:类
{
...的内容...
}

然而,这并不适用于方法。这是完全正常的:

 公共类MyClass的< T> 
,其中T:类
{
私人MyOtherClass< T,U>方法< U>()其中U:类
{
...内容...
}
}


I have the following problem:

public class MyClass<T> where T : class
{
    private MyOtherClass<T, U> variable where U : class;
    ... content ...
}
public class MyOtherClass<T, U> where T : class where U : class
{
    ... content ...
}

Is that possible somehow?

If you want to make the type of a field or property of MyClass generic based on some type parameter U, you have to declare that as a type parameter of MyClass:

public class MyClass<T, U> 
    where T : class 
    where U : class
{
    private MyOtherClass<T, U> variable;
    ... content ...
}
public class MyOtherClass<T, U>
    where T : class 
    where U : class
{
    ... content ...
}

However, that doesn't apply to methods. This is perfectly fine:

public class MyClass<T> 
    where T : class 
{
    private MyOtherClass<T, U> Method<U>() where U : class
    {
        ... content ...
    }
}