C#枚举及控件属性有关问题
C#枚举及控件属性问题
先说目的: 要求控件的属性是下拉列表框(拿字符串做例子)
这样的是可以:
public partial class ViewItem : UserControl
{
private RelationOpert relations;
public RelationOpert Relations
{
get { return relations; }
set { relations = value; }
}
}
public enum RelationOpert
{
Top = 0,
Left = 1,
Bottom = 2,
Right = 3
}
可是我枚举特殊
public enum RelationOpert
{
> 0,
< ,
>=,
<=
}
该怎么办啊,谢谢高手指点。
------解决方案--------------------
特殊字符,编译都通不过。当然不可能。
写到枚举的Description里,用反射取出来还能实现。
------解决方案--------------------
foreach (FieldInfo field in typeof(RelationOpert).GetFields(BindingFlags.Public
------解决方案--------------------
BindingFlags.Static))
{
object[] atts = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
...
}
------解决方案--------------------
------解决方案--------------------
先说目的: 要求控件的属性是下拉列表框(拿字符串做例子)
这样的是可以:
public partial class ViewItem : UserControl
{
private RelationOpert relations;
public RelationOpert Relations
{
get { return relations; }
set { relations = value; }
}
}
public enum RelationOpert
{
Top = 0,
Left = 1,
Bottom = 2,
Right = 3
}
可是我枚举特殊
public enum RelationOpert
{
> 0,
< ,
>=,
<=
}
该怎么办啊,谢谢高手指点。
------解决方案--------------------
特殊字符,编译都通不过。当然不可能。
写到枚举的Description里,用反射取出来还能实现。
------解决方案--------------------
foreach (FieldInfo field in typeof(RelationOpert).GetFields(BindingFlags.Public
------解决方案--------------------
BindingFlags.Static))
{
object[] atts = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
...
}
------解决方案--------------------
class Program
{
static void Main(string[] args)
{
var list = GetEnumDescription(typeof(Test));
}
public static List<KeyValuePair<int, string>> GetEnumDescription(Type enumType)
{
var descriptions = new List<KeyValuePair<int, string>>();
FieldInfo[] fis = enumType.GetFields();
foreach (var fi in fis)
{
if (fi.FieldType == typeof(Int32)) continue;
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.
GetCustomAttributes(typeof(DescriptionAttribute), false);
int key = (int)fi.GetValue(null);
string desc = (attributes.Length > 0) ? attributes[0].Description : fi.Name;
descriptions.Add(new KeyValuePair<int, string>(key, desc));
}
return descriptions;
}
}
public enum Test
{
[Description(">")]
A,
B,
C
}
------解决方案--------------------
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.propertyGrid1.SelectedObject = new My();
TypeConverter convert = new MyEnumConverter(typeof(RelationOp));
string g = convert.ConvertToInvariantString(RelationOp.Greater); // >