为什么Type.IsByRef String类型返回false,如果字符串是引用类型?类型、字符串、IsByRef、Type

由网友(我这么帅当然是女孩子)分享简介:根据这的字符串(或字符串)是引用类型。 According to this a string (or String) is a reference type. 然而考虑到:Type t = typeof(string);然后if (t.IsByRef) ... 返回false returns false...

根据这的字符串(或字符串)是引用类型。

According to this a string (or String) is a reference type.

然而考虑到:

Type t = typeof(string);

然后

if (t.IsByRef) ...    

返回false

returns false

为什么?

编辑:经过一番快速测试,我显然误解IsByRef的目的... 因为即使使用到位字符串的类名,以及返回false。我正在写一个泛型类和想要测试如果一个的时候,一般是通过实例化的类型是一个值或引用类型。一个人怎么测试呢?

After some quick testing, I'm obviously misunderstanding the purpose of IsByRef... as even using a class name in place of 'string' ,returns false as well. I'm writing a generic class and want to test if one the types passed in when the generic is instantiate is a value or reference type. How does one test for this?

推荐答案

您应该使用 IsValueType 来代替:

bool f = !typeof (string).IsValueType; //return true;

至于 IsByRef ,这个属性的目的是确定由裁判或值的参数是传入的方法。

As for IsByRef, the purpose of this property is to determine whether the parameter is passed into method by ref or by value.

例如你有一个方法, A 是由裁判通过:

Example you have a method which a is passed by ref:

public static void Foo(ref int a)
{
}

您可以决定是否 A 是通过引用传递与否:

You can determine whether a is pass by reference or not:

  bool f = typeof (Program).GetMethod("Foo")
                                 .GetParameters()
                                 .First()
                                 .ParameterType
                                 .IsByRef;   //return true
阅读全文

相关推荐

最新文章