访问表格的成员可能会导致运行时异常,因为它是一个元帅,被引用类的领域 [英] Accessing a member on Form may cause a runtime exception because it is a field of a marshal-by-reference class

查看:453
本文介绍了访问表格的成员可能会导致运行时异常,因为它是一个元帅,被引用类的领域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的形式访问的成员可能会导致 运行时异常,因为它是一个元帅,被引用的类

"Accessing a member on Form may cause a runtime exception because it is a field of a marshal-by-reference class"

我知道这是什么警告,并知道如何解决它。

I know what is this warning and know how to solve it.

的问题是,为什么这会带来一个运行时错误?

the question is why this could bring a runtime error?

推荐答案

您可能正在谈论的警告CS1690,摄制code:

You are probably talking about warning CS1690, repro code:

public class Remotable : MarshalByRefObject {
    public int field;
}
public class Test {
    public static void Run() {
        var obj = new Remotable();
        // Warning CS1690:
        Console.WriteLine(obj.field.ToString());
    }
}

在一个远程情况下,Test.Run方法将与可远程对象的代理。构建代理的属性,方法或事件是不是太大的问题,创建包含替代一个方法表只是一个问题。字段是一个问题,但是,没有什么钩。对于MBRO,JIT编译器不再生成code直接访问现场,它注入调用内置的CLR,JIT_GetField32()在这种情况下,一个辅助方法。

In a remoting scenario, the Test.Run method will work with a proxy of the Remotable object. Building a proxy for a property, method or event isn't much of a problem, just a matter of creating a MethodTable that contains the substitutes. Fields are a problem however, there's nothing to 'hook'. For a MBRO, the JIT compiler no longer generates code to access the field directly, it injects a call to a helper method built into the CLR, JIT_GetField32() in this case.

如果对象是一个代理,并且使用远程处理管道,以获得远程值如果是这种情况即辅助检查。或者只是访问现场直接,如果事实并非如此。制作的ToString()调用但要求将装箱的值。这是一个问题,拳隔离代理的价值。有没有办法,以确保装箱值的总是的远程访问该值的精确副本。调用JIT_GetField32()再次每当ToString()方法使用值格式化字符串是不可能的。

That helper checks if the object is a proxy and uses the remoting plumbing to obtain the remote value if that's the case. Or just accesses the field directly if it isn't. Making the ToString() call however requires the value to be boxed. That's a problem, boxing isolates the value from the proxy. There is no way to ensure that the boxed value is always an accurate copy of the remoted value. Calling JIT_GetField32() again whenever the ToString() method uses the value to format the string isn't possible.

的变通方法CS1690很简单,只需要复制该字段值中的局部变量。现在有一点是清楚的是,code正在与一个副本,从未有一个惊喜因此,编译器不会发出警告。

The workaround for CS1690 is simple, just copy the field value in a local variable. Now it is crystal clear that the code is working with a copy and there is never a surprise so the compiler won't have to emit a warning.

public static void Run() {
    var obj = new Remotable();
    var value = obj.field;
    Console.WriteLine(value.ToString());     // No warning
}

这篇关于访问表格的成员可能会导致运行时异常,因为它是一个元帅,被引用类的领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆