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

2024-06-30

我有以下问题:

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 ...
}

这有可能吗?


如果你想将字段或属性的类型设置为MyClass基于某些类型参数的泛型U,您必须将其声明为类型参数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 ...
}

但是,这不适用于方法。这完全没问题:

public class MyClass<T> 
    where T : class 
{
    private MyOtherClass<T, U> Method<U>() where U : class
    {
        ... content ...
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

c# 变量声明上的泛型,这可能吗? 的相关文章

随机推荐