C# 泛型:引用类型与值类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/600525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:50:01  来源:igfitidea点击:

C# Generics: Reference types vs. Value Types

c#generics

提问by

I've faced a lot of confusion with regards to differences between generic reference types vs. generic value types whilst writing my API.

在编写我的 API 时,我在泛型引用类型与泛型值类型之间的差异方面遇到了很多困惑。

What are the differences with regards to constraints and functionalities (most important/easily overlooked) between the two?

两者在约束和功能(最重要/最容易被忽视)方面有什么区别?

class ReferenceGeneric <T> where ???
{

}

and

struct ValueGeneric <T>: where ???
{

}

Edit #1Just to clarify the question and what I am after: I want to know what you can do with Generic reference types AND cannot do with generic value types (and vice versa)

编辑 #1只是为了澄清问题和我所追求的:我想知道你可以用泛型引用类型做什么,不能用泛型值类型做什么(反之亦然)

Edit #2Further clarifications: How can T be constrained if generic type is reference or value type? Are there differences as to how each type can be constrained?

编辑 #2进一步说明:如果泛型类型是引用或值类型,如何约束 T?每种类型的约束方式是否存在差异?

采纳答案by Jon Skeet

Be aware that anything declared as a struct is alwaysa value type, and anything declared as a class is alwaysa reference type. In other words, List<int>is still a reference type, and if you had:

请注意,声明为结构的任何内容始终是值类型,而声明为类的任何内容始终是引用类型。换句话说,List<int>仍然是一个引用类型,如果你有:

struct Foo<T>
{
    T value;
}

then Foo<string>would still be a value type.

那么Foo<string>仍然是一个值类型。

As for what you can dowith the generic types - they really just follow the normal rules for value types and reference types; as for what you can do with an value of type Twithinthe type, that depends on whether/how Tis constrained. It doesn't vary based on whether the generic type itself is a struct or a class though.

至于你可以用泛型什么——它们实际上只是遵循值类型和引用类型的正常规则;至于您可以对类型T的类型值做什么,这取决于是否/如何T受到约束。不过,它不会根据泛型类型本身是结构体还是类而有所不同。

EDIT: Sasha mentions Nullable<T>in the comments. I'm not sure what "exception" is meant here - other than Nullable<T>doesn't satisfy either the "where T : struct" or "where T : class" constraint. It's still a value type though (which is part of the point).

编辑:萨沙Nullable<T>在评论中提到。我不确定这里的“异常”是什么意思——除了Nullable<T>不满足“ where T : struct”或“ where T : class”约束。尽管如此,它仍然是一个值类型(这是重点的一部分)。

回答by C. Ross

In response to Edit2: You can limit the types allowed to reference or value by the following:

响应 Edit2: 您可以通过以下方式限制允许引用或值的类型:

Reference:

参考:

class ReferenceGeneric <T> where T: class
{

}

Value:

价值:

struct ValueGeneric <T> where T: struct 
{


}

From the following page on MSDN http://msdn.microsoft.com/en-us/library/d5x73970.aspx

从 MSDN 上的以下页面 http://msdn.microsoft.com/en-us/library/d5x73970.aspx