Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 什么是;其中T:somevalue“;什么意思?_C#_Generics_Constraints - Fatal编程技术网

C# 什么是;其中T:somevalue“;什么意思?

C# 什么是;其中T:somevalue“;什么意思?,c#,generics,constraints,C#,Generics,Constraints,其中T:somevalue是什么意思?我刚刚看到一些代码,上面写着where T:Attribute。我认为这与泛型有关,但我不确定这意味着什么或它在做什么 有人知道吗?它是a,这意味着给定给泛型类或方法的类型T必须从类属性继承 例如: public class Foo<T> : where T : Attribute { public string GetTypeId(T attr) { return attr.TypeId.ToString(); } // ..

其中T:somevalue
是什么意思?我刚刚看到一些代码,上面写着
where T:Attribute
。我认为这与泛型有关,但我不确定这意味着什么或它在做什么

有人知道吗?

它是a,这意味着给定给泛型类或方法的类型
T
必须从类
属性继承

例如:

public class Foo<T> : 
   where T : Attribute
{
    public string GetTypeId(T attr) { return attr.TypeId.ToString(); }
 // ..
}

Foo<DescriptionAttribute> bar; // OK, DescriptionAttribute inherits Attribute
Foo<int> baz; // Compiler error, int does not inherit Attribute
您还可以对类型施加其他约束;发件人:

其中T:struct

类型参数必须是值 类型。除可为Null之外的任何值类型 可以指定

其中T:class

类型参数必须是引用 类型;这也适用于任何类别, 接口、委托或数组类型

其中T:new()

类型参数必须具有公共 无参数构造函数。使用时 再加上其他约束条件 必须指定new()约束 最后

其中T:

类型参数必须为或派生 从指定的基类

其中T:

类型参数必须为或实现 指定的接口。倍数 接口约束可以是 明确规定。约束界面 也可以是通用的

其中T:U

为T提供的类型参数必须为 是论点或从论点中衍生出来的 为美国供应。这被称为裸体 类型约束

该子句用于限制使用泛型时可以传递的参数。创建泛型类时,最好指定参数类型,具体取决于您计划在类中使用T的方式。如果它不是System.Object所能做的,那么最好使用,因为与运行时相比,您将得到编译时错误

范例

如果你创建了一个类

class Person<T> where T : System.IComparable<T>
{
   //can now use CompareTo
}
类人员,其中T:System.i可比较
{
//现在可以使用CompareTo
}

不能向此类传递任何未实现IComparable的内容。因此,现在可以安全地对传递到Person类的任何对象使用CompareTo。

这是一种限制用作泛型参数的类型的方法。因此:

where T : SomeType

意味着T必须从SomeType派生,或者实现接口SomeType。另外,正如其他人所说,您也有以下内容:

  • new()-T必须具有默认构造函数
  • 类-T必须是引用类型
  • struct-T必须是值类型

+1这是相当全面的。我希望我能找到答案。
where T : SomeType