简体   繁体   English

为什么C#结构不能返回对其成员字段的引用?

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

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. 此代码引发编译错误CS8170,但如果Foo是一个类,它不会。 Why can a structure not return a member as a reference? 为什么结构不能将成员作为引用返回?

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. 但是,我确实认为它是通过返回对struct成员的引用来实现你想要的,然后你可以编组以获得原始值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 C# struct 方法不能返回对字段的引用,但非成员方法可以? - Why can't a C# struct method return a reference to a field, but a non-member method can? 为什么我不能从C#的内部类中引用静态成员? - Why can't I reference a static member from an inner class in C#? 我可以在C#中将结构返回为字段初始值设定项吗? - Can I return structure as field initializers in C#? c# 如何在不使用 arrays 的结构中创建长字段(例如 >128 字节)。 我的结构中不能有任何引用类型字段 - c# How do I create a long (>128 bytes for example) field in a structure without using arrays. I can't have any reference type fields in the structure 为什么我不能直接在C#中编辑列表成员 - Why can't I edit a List member directly in C# 返回一个与声明的结构不同的结构,为什么它是正确的? C# - return a structure different from the declared structure, why can it be correct? C# 无法在C#代码中引用图像ID。 为什么? - Can't reference Image ID in C# Code. Why? 为什么我不能在C#中访问私有字段? - Why can't I access private field in C#? 引用c#Object Field作为字符串传递的名称 - Reference an c# Object Field by its name passed as a string 在 C# 中,为什么我不能从其接口签名将基接口类型作为其返回类型的 function 返回派生接口类型? - In C#, why can't I return a derived interface type from a function whose interface signature has the base interface type as its return type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM