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

前端 未结 4 421
别跟我提以往
别跟我提以往 2020-12-17 10:32

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

I know what this warnin

4条回答
  •  不知归路
    2020-12-17 11:03

    In addition to the suggestion from @hans-passant, I think another useful way to fix this warning is by turning your field into a property.

    public class Remotable : MarshalByRefObject {
        public int field;
    }
    

    could become

    public class Remotable : MarshalByRefObject {
        public int field { get; set }
    }
    

    and you no longer get any warnings! (Hans Passant already has an excelent explanation for this, see his post)

    Obviously, you can not always alter the object you are working with (example: WinForms where the fields are generated for you) so you might have to fallback to using a temporary variable.

提交回复
热议问题