ref或out参数必须是可分配的变量吗?

时间:2018-12-24 11:01:45

标签: c# windows winforms ref

错误:

  

ref或out参数必须是可分配的变量

代码:

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public class OAKListView : ListView
{
    protected override void OnHandleCreated(EventArgs e)
    {
        base.OnHandleCreated(e);

        this.WndProc(ref new Message()
        {
            HWnd = this.Handle,
            Msg = 4150,
            LParam = (IntPtr)43,
            WParam = IntPtr.Zero
        });
    }
}

显示错误

  

this.WndProc(ref new Message()

2 个答案:

答案 0 :(得分:3)

错误清楚地说明了这一点。您需要一个可分配的变量

protected override void OnHandleCreated(EventArgs e)
{
    base.OnHandleCreated(e);
    var message = new Message()
    {
        HWnd = this.Handle,
        Msg = 4150,
        LParam = (IntPtr)43,
        WParam = IntPtr.Zero
    };
    this.WndProc(ref message);
}

答案 1 :(得分:2)

您的ref参数不是可分配的变量。不应该同时创建Message类的新实例并作为引用传递。调用方法应该填入内存中的某个位置。您的通话中没有这样的东西。这样会编译:

var message = new Message()
{
    HWnd = this.Handle,
    Msg = 4150,
    LParam = (IntPtr)43,
    WParam = IntPtr.Zero
});

this.WndProc(ref message);