Why can't a C# structure return a reference to its member field?

前端 未结 1 2013
南笙
南笙 2021-02-19 13:18
struct Foo {
    int i;
    public ref int I => ref i;
}

This code raises compile error CS8170, but if Foo is a class, it doesn\'t. Why

相关标签:
1条回答
  • 2021-02-19 14:18

    I think I found a way around it:

    class Program
    {
        static void Main(string[] args)
        {
            Foo temp = new Foo(99);
            Console.WriteLine($"{Marshal.ReadInt32(temp.I)}");
            Console.ReadLine();
        }
    }
    struct Foo
    {
        int i;
        public IntPtr I;
    
        public Foo(int newInt)
        {
            i = newInt;
            I = GetByRef(i);
        }
        static unsafe private IntPtr GetByRef(int myI)
        {
            TypedReference tr = __makeref(myI);
            int* temp = &myI;
            IntPtr ptr = (IntPtr)temp;
            return ptr;
        }
    }
    

    Not that its a good idea- too many dire warnings. However, I do believe it is achieving what you want by returning a reference to the struct member, which you can then marshal to get the original value.

    0 讨论(0)
提交回复
热议问题