在c#.Net中创建基于索引的类
我有一些类,希望使用索引或类似的方法访问它们的属性在c#.Net中创建基于索引的类,c#,.net,oop,C#,.net,Oop,我有一些类,希望使用索引或类似的方法访问它们的属性 ClassObject[0]或更好的将是ClassObject[“PropName”] 而不是这个 ClassObj.PropName. 谢谢您需要索引器: 公共类MyClass { 私有字典_innerdiodictionary=新字典(); 公共对象此[字符串键] { 获取{return _innerDictionary[key];} 设置{u innerDictionary[key]=value;} } } //用法 MyClass c
ClassObject[0]
或更好的将是ClassObject[“PropName”]
而不是这个
ClassObj.PropName.
谢谢您需要索引器:
公共类MyClass
{
私有字典_innerdiodictionary=新字典();
公共对象此[字符串键]
{
获取{return _innerDictionary[key];}
设置{u innerDictionary[key]=value;}
}
}
//用法
MyClass c=新的MyClass();
c[“某物”]=新对象();
这是记事本编码,所以请谨慎对待,不过索引器语法是正确的
如果您想使用它以便可以动态访问属性,那么您的索引器可以使用反射将键名称作为属性名称
或者,查看dynamic
对象,特别是ExpandoObject
,可以将其转换为IDictionary
,以便基于文字字符串名称访问成员
public string this[int index]
{
get
{ ... }
set
{ ... }
}
这将为您提供一个索引属性。你可以设置你想要的任何参数。如何使用索引器和你想要的示例。我不确定你在这里的意思,但我要说的是,你必须使
类对象
成为某种IEnumerable
类型,像列表
或字典
一样使用它来瞄准这里。你可以这样做,伪代码:
用过之后,就像
MyClass cl = new MyClass();
cl["MyClassProperty"] = "cool";
请注意,这并不是完整的解决方案,因为如果希望具有非公共属性/字段、静态属性/字段等,则需要在反射访问期间“播放”BindingFlags 请出示一些代码。。。您的财产类型是什么?请写下您为什么希望通过这种方式访问这些财产?
public class MyClass
{
public object this[string PropertyName]
{
get
{
Type myType = typeof(MyClass);
System.Reflection.PropertyInfo pi = myType.GetProperty(PropertyName);
return pi.GetValue(this, null); //not indexed property!
}
set
{
Type myType = typeof(MyClass);
System.Reflection.PropertyInfo pi = myType.GetProperty(PropertyName);
pi.SetValue(this, value, null); //not indexed property!
}
}
}
MyClass cl = new MyClass();
cl["MyClassProperty"] = "cool";