命名索引属性?一些语言——比如Delphi——有一种非常方便的创建索引器的方法:不仅可以对整个类进行索引,甚至可以对单个属性进行索引,例如:typeTMyClass=class(TObject)protectedfunctionGetMyProp(index:integer):string;程序SetMyProp(索引:整数;值:字符串);publicpropertyMyProp[index:integer]:string读取GetMyProp写入SetMyProp;结尾;这可以很容易地使用:varc:TMyClass;开始c=TMyClass.Create;c.MyProp[5]:='Alamakota';c.免费;结尾;有没有办法在C#中轻松实现相同的目标?众所周知的解决方案是创建一个代理类:publicclassMyClass{publicclassMyPropProxy{privateMyClassc;//ctor等publicstringthis[intindex]{get{returnc.list[index];}设置{c。列表[索引]=值;}}}私有列表列表;私有MyPropProxymyPropProxy;//ctor等publicMyPropProxyMyProp{get{returnmyPropProxy;但是(除此之外实际上解决了问题),这种解决方案主要只是引入缺点:但是还有另一种方法。它也会污染一些代码,但绝对比前一个少很多:publicinterfaceIMyProp{stringthis[intindex]{get;}}publicclassMyClass:IMyProp{privateList列表;字符串IMyProp.this[intindex]{get{returnlist[index];}设置{列表[索引]=值;}}//ctor等publicIMyPropMyProp{get{returnthis;}}}优点:缺点:这是将索引属性引入C#的最简单(就代码长度和复杂性而言)的方式。当然,除非有人发布更短更简单的内容。以上是C#学习教程:NamedindexedpropertiesinC#?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
