是否有可能通过反射来获取属性的私人二传手? [英] Is it possible to get a property's private setter through reflection?

查看:107
本文介绍了是否有可能通过反射来获取属性的私人二传手?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个自定义序列是由反射设置对象属性的作品。序列化类标记有Seri​​alizable属性和所有序列化的属性也标记。例如,下面的类是可序列化:

I wrote a custom serializer that works by setting object properties by reflection. Serializable classes are tagged with serializable attribute and all serializable properties are also tagged. For example, the following class is serializable:

[Serializable]
public class Foo
{
   [SerializableProperty]
   public string SomethingSerializable {get; set;}

   public string SometthingNotSerializable {get; set;}
}

在串行被要求反序列化 SomethingSerializable ,它得到属性的设置方法,并用它做这样的事情来进行​​设置:

When the serializer is asked to deserialize SomethingSerializable, it gets the set method of the property and uses it to set it by doing something like this:

PropertyInfo propertyInfo; //the property info of the property to set
//...//
if (propertyInfo.CanWrite && propertyInfo.GetSetMethod() != null)
{
   propertyInfo.GetSetMethod().Invoke(obj, new object[]{val});
}



然而,这工作得很好,我怎样才能使属性setter只能访问序列化?如果二传手是私有的:

This works fine, however, how can I make the property setter accessible only to the serializer? If the setter is private:

public string SomethingSerializable {get; private set;}



然后调用 propertyInfo.GetSetMethod()在串行返回null。有什么办法来访问私人二传手或其他任何方式,以确保只有串行器可以访问二传手?序列化程序不能保证在同一个组件。

then the call to propertyInfo.GetSetMethod() returns null in the serializer. Is there any way to access the private setter or any other way to ensure that only the serializer can access the setter? The serializer is not guaranteed to be in the same assembly.

推荐答案

正如你已经想通了,要访问一个非公开的setter方法​​之一是如下:

As you already figured out, one way to access a non-public setter is as follows:

PropertyInfo property = typeof(Type).GetProperty("Property");
property.GetSetMethod(true).Invoke(obj, new object[] { value });

有另一种方法,不过,如果我没有记错的:

There is another way, though, if I recall correctly:

PropertyInfo property = typeof(Type).GetProperty("Property");
property.SetValue(obj, value, BindingFlags.NonPublic | BindingFlags.Instance, null, null, null);

这篇关于是否有可能通过反射来获取属性的私人二传手?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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