gpt4 book ai didi

c# - "where T : somevalue"是什么意思?

转载 作者:可可西里 更新时间:2023-11-01 08:31:51 24 4
gpt4 key购买 nike

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

有人知道吗?

最佳答案

这是一个constraint on a type parameter ,表示类型 T赋予泛型类或方法的必须继承自类 Attribute

例如:

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 类型的对象进行操作知道任何东西都是 T也必须是 Attribute .

在上面的例子中,GetTypeId 没问题查询 TypeIdattr因为TypeIdAttribute 的属性,因为 attrT它必须是继承自 Attribute 的类型.

约束也可以用在泛型方法上,效果一样:

public static void GetTypeId<T>(T attr) where T : Attribute
{
return attr.TypeId.ToString();
}

您还可以对类型施加其他约束;来自 MSDN :

where T: struct

The type argument must be a value type. Any value type except Nullable can be specified.

where T : class

The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

where T : new()

The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.

where T : <base class name>

The type argument must be or derive from the specified base class.

where T : <interface name>

The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.

where T : U

The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.

关于c# - "where T : somevalue"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/622264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com