您可以使用PropertyDescriptor
ofSystem.ComponentModel
进行惰性编码。假设您要迭代公共实例方法(不是静态方法),您可以尝试以下示例:
测试 类:
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();
}
您还可以检查循环中的值是否为空。SetDefaultStringValues
方法参数可以是任何对象实例。您可以将其更改为SetDefaultStringValues(this object o)
并将其用作定义的类实例的扩展方法。