如何在运行时操作用户定义类的属性
本文关键字:定义 属性 用户 操作 运行时 | 更新日期: 2023-09-27 17:58:21
我有一个巨大的用户定义的类,它有很多属性,其中一些属性必须设置为某个值。
更具体地说,在这个用户定义的类中,所有类型为字符串的公共属性都必须在执行结束时"清空"。
所以我一个接一个地找到了所有的公共属性(比如300个属性),并用我的300行代码为它们赋值。我为解决这个问题所做的,做了我需要的,但当然并没有让我满意。
因此,我决定在C#中编写一个Helper方法(作为Extension方法),它遍历对象实例的属性并动态访问/操作它们。我在这里看到了一些关于迭代属性的类似问题,但到目前为止还没有看到任何关于更改属性值的问题。以下是我尝试过的:
public static void SetDefaultStringValues(this Object myObject)
{
PropertyInfo[] aryProperties = entityObject.GetType().GetProperties();
foreach (object property in aryProperties)
{
if (property is String)
{
//property = String.Empty;
}
}
}
评论部分必须是我设置变量的那一行,但这并不是一个真正的成功故事:)我会感谢任何帮助。
使用PropertyInfo。SetValue方法,更多关于此的信息,请参阅
您可以使用System.ComponentModel
的PropertyDescriptor
进行延迟编码。假设您想迭代公共实例方法(而不是静态方法),您可以尝试以下示例:
测试 类:
public class TestClass
{
private int mIntMemeber = 0; // # to test int type
private string mStringMember = "abc"; // # to test string type (initialized)
private string mNullStringMember = null; // # to test string type (null)
private static string mStaticNullStringMember; // # to test string type (static)
// # Defining properties for each member
public int IntMember
{
get { return mIntMemeber; }
set { mIntMemeber = value; }
}
public string StringMember
{
get { return mStringMember; }
set { mStringMember = value; }
}
public string NullStringMember
{
get { return mNullStringMember; }
set { mNullStringMember = value; }
}
public static string StaticNullStringMember
{
get { return mStaticNullStringMember; }
set { mStaticNullStringMember = value; }
}
}
SetDefaultStringValues()扩展方法:
public static string SetDefaultStringValues(this TestClass testClass)
{
StringBuilder returnLogBuilder = new StringBuilder();
// # Get all properties of testClass instance
PropertyDescriptorCollection propDescCollection = TypeDescriptor.GetProperties(testClass);
// # Iterate over the property collection
foreach (PropertyDescriptor property in propDescCollection)
{
string name = property.Name;
Type t = property.PropertyType; // # Get property type
object value = property.GetValue(testClass); // # Get value of the property (value that member variable holds)
if (t == typeof(string)) // # If type of propery is string and value is null
{
property.SetValue(testClass, String.Empty); // # Set value of the property (set member variable)
value = String.Empty; // # <-- To prevent NullReferenceException when printing out
}
returnLogBuilder.AppendLine("*****'nName:'t{0}'nType:'t{1}'nValue:'t{2}", name, t.ToString(), value.ToString());
}
returnLogBuilder.AppendLine("*****");
return returnLogBuilder.toString();
}
您还可以检查循环中的值是否为null。SetDefaultStringValues
方法参数可以是任何对象实例。您可以将其更改为SetDefaultStringValues(this object o)
,并将其用作已定义类实例的扩展方法。
您需要不同的语法来检查属性类型;此外,您应该检查该属性是否具有公共setter。
if (property.PropertyType == typeof(string) && property.GetSetMethod() != null)
property.SetValue(entityObject, "");
foreach (PropertyInfo property in aryProperties)
{
if (property.PropertyType == typeof(string) && property.CanWrite)
{
property.SetValue(myObject, "", null);
}
}