您的代码没有问题,对于有些控件是没有FlatStyle属性的,可以用反射检测一下这个类型有没有此属性,没有则不赋值。
public static bool HasProperty(this object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName) != null;
}
https://stackoverflow.com/questions/15341028/check-if-a-property-exist-in-a-class
如果上面的方法返回false,则表示控件是没有FlatStyle属性,跳过赋值语句。
同样道理,赋值也需要改成反射以通过编译:
https://stackoverflow.com/questions/619767/set-object-property-using-reflection
Yes, you can use Type.InvokeMember()
:
using System.Reflection;
MyObject obj = new MyObject();
obj.GetType().InvokeMember("Name",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
Type.DefaultBinder, obj, "Value");
This will throw an exception if obj
doesn't have a property called
Name
, or it can't be set.
Another approach is to get the metadata for the property, and then set it. This will allow you to check for the existence of the property, and verify that it can be set:
using System.Reflection;
MyObject obj = new MyObject();
PropertyInfo prop = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if(null != prop && prop.CanWrite)
{
prop.SetValue(obj, "Value", null);
}
专注于.NET ERP/CRM开发框架,C/S架构,SQL Server + ORM(LLBL Gen Pro) + Infragistics WinForms