4

我有以下问题:

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

这有可能吗?

4

3 回答 3

3

如果要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 ...
    }
}
于 2013-07-20T02:19:46.790 回答
1

看起来您想要MyClass<T>包含对MyOtherClass<T, U>两个Ts 匹配但任何U被接受的位置的引用。如果这是您要尝试做的事情,那么现有答案可能无济于事,因为具有通用U参数的方法仍然需要用户指定U.

具有类型参数(尤其是多个)的类应该继承/实现一些不太通用的东西来支持这种情况。例如:

public interface IOtherThing<T> {
    T Value1 { get; }
    object Value2 { get; }
}

public class MyOtherClass<T, U> : IOtherThing<T> {
    public T Value1 { get { ... } }
    public U Value2 { get { ... } }
    object IOtherThing<T>.Value2 { get { return Value2; } }
}

现在,MyClass<T>可以将变量声明为IOtherThing<T>,可以将其分配给任何MyOtherClass<T, U>

于 2013-07-20T03:22:25.410 回答
1

要直接回答标题中的问题,您不能这样做,因为它是typevariable字段MyOtherClass<T, U>,这意味着MyOtherClass 定义类型参数T并且U- 正如您所拥有的那样!

Tof与of 不同MyClass<T>,因为泛型类型约束的声明属于泛型类型本身,而不属于使用它的类型——这很好!TMyOtherClass<T, U>

如果可能的话,这样的类型:

public class SomeRepository<TEntity>
    where TEntity : IEntity { /* ... */}

可以这样使用:

public class SomeService
{
    private SomeRepository<TEntity> _someRepo where TEntity : INotAnEntity
}

接口、类和方法可以是通用的(即能够定义类型约束);字段和属性不能,但它们可以是泛型类型。

于 2013-07-20T02:32:58.337 回答