WEB开发网
开发学院软件开发C语言 C#中访问私有成员 阅读

C#中访问私有成员

 2010-09-30 22:43:54 来源:WEB开发网   
核心提示: 3、设置私有成员的值:publicstaticvoidSetPrivateField(thisobjectinstance,stringfieldname,objectvalue){BindingFlagsflag=BindingFlags.Instance|BindingFlags.NonPu

3、设置私有成员的值:

public static void SetPrivateField(this object instance, string fieldname, object value) 
{ 
    BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; 
    Type type = instance.GetType(); 
    FieldInfo field = type.GetField(fieldname, flag); 
    field.SetValue(instance, value); 
} 

4、设置私有属性的值:

public static void SetPrivateProperty(this object instance, string propertyname, object value) 
{ 
    BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; 
    Type type = instance.GetType(); 
    PropertyInfo field = type.GetProperty(propertyname, flag); 
    field.SetValue(instance, value, null); 
} 

5、调用私有方法:

public static T CallPrivateMethod<T>(this object instance, string name, params object[] param)
{
    BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic;
    Type type = instance.GetType();
    MethodInfo method = type.GetMethod(name, flag);
    return (T)method.Invoke(instance, param);
}

测试:

下面我们使用一个测试类,进行测试。新建一个类库项目,测试的类代码如下:

public class TestClass 
{ 
 
  public TestClass() 
  { 
    privatefield1 = 1; 
    privatefield2 = 99; 
    PrivateFieldA = "Lo"; 
    PrivateFieldB = "ve"; 
  } 
 
  private int privatefield1; 
  private int privatefield2; 
  
 
  private string PrivateFieldA 
  { 
    get; 
    set; 
  } 
  private string PrivateFieldB 
  { 
    get; 
    set; 
  } 
 
 
  private int Add() 
  { 
    return privatefield1 + privatefield2; 
  } 
  private string Join() 
  { 
    return PrivateFieldA + PrivateFieldB; 
  } 
}

Tags:访问 私有 成员

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接