Why does Type.IsByRef for type String return false if String is a reference type?

前端 未结 3 504
甜味超标
甜味超标 2021-01-01 23:36

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

Yet given:

Type t = typeof(string);

then

if (t.IsBy         


        
相关标签:
3条回答
  • 2021-01-01 23:52

    There are "reference types" -- for which we have !type.IsValueType -- and then there are types that represent references to anything -- whether their targets are value types or reference types.

    When you say void Foo(ref int x), the x is said to be "passed by reference", hence ByRef.
    Under the hood, x is a reference of the type ref int, which would correspond to typeof(int).MakeReferenceType().

    Notice that these are two different kinds of "reference"s, completely orthogonal to each other.

    (In fact, there's a third kind of "reference", System.TypedReference, which is just a struct.
    There's also a fourth type of reference, the kind that every C programmer knows -- the pointer, T*.)

    0 讨论(0)
  • 2021-01-01 23:59

    You want to check if it is a value type.

    typeof(object).IsValueType :- false
    typeof(int).IsValueType :- true
    
    0 讨论(0)
  • 2021-01-02 00:02

    You should use IsValueType instead:

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

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

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

    public static void Foo(ref int a)
    {
    }
    

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

      bool f = typeof (Program).GetMethod("Foo")
                                     .GetParameters()
                                     .First()
                                     .ParameterType
                                     .IsByRef;   //return true
    
    0 讨论(0)
提交回复
热议问题