C#泛型的变量声明,这可能吗? [英] c# Generic on variable declaration, is this possible?

查看:120
本文介绍了C#泛型的变量声明,这可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:



<预类=郎-CS prettyprint-覆盖> 公共类MyClass的< T>其中T:类
{
私人MyOtherClass< T,U>变量中,其中U:类;
...的内容...
}
公共类MyOtherClass< T,U>其中T:类,其中U:类
{
...的内容...
}

这是可能以某种方式?


解决方案

如果你想使一个字段或属性的类型的 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 ...
    }
}

这篇关于C#泛型的变量声明,这可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆