IComparable<T> 接口:

public class MyGenericClass<T> where T:IComparable { }

注意:有关查询表达式中的 where 子句的更多信息,请参见 where 子句(C# 参考)

这样的约束一经使用,就必须出现在该类型参数的所有其他约束之前。

class MyClass<T, U>
    where T : class
    where U : struct
{ }

例如:

public class MyGenericClass<T> where T : IComparable, new()
{
    // The following line is not possible without new() constraint:
    T item = new T();
}

new() 约束出现在 where 子句的最后。

对于多个类型参数,每个类型参数都使用一个 where 子句,例如:

interface IMyInterface
{
}

class Dictionary<TKey, TVal>
    where TKey : IComparable, IEnumerable
    where TVal : IMyInterface
{
    public void Add(TKey key, TVal val)
    {
    }
}

还可以将约束附加到泛型方法的类型参数,例如:

public bool MyMethod<T>(T t) where T : IMyInterface { }

请注意,对于委托和方法两者来说,描述类型参数约束的语法是一样的:

delegate T MyDelegate<T>() where T : new()

参考:https://msdn.microsoft.com/zh-cn/library/d5x73970.aspx

 

相关文章:

  • 2022-12-23
  • 2021-08-15
  • 2022-12-23
  • 2022-12-23
  • 2021-12-26
  • 2022-12-23
猜你喜欢
  • 2021-08-02
  • 2022-12-23
  • 2021-10-10
  • 2022-02-26
相关资源
相似解决方案