一个更通用,更安全,可重复使用的解决方案,您的问题可能是实现一个通用的,“参数”属性类,如下:
// Generic, parameterized (indexed) "property" template
public class Property<T>
{
// The internal property value
private T PropVal = default(T);
// The indexed property get/set accessor
// (Property<T>[index] = newvalue; value = Property<T>[index];)
public T this[object key]
{
get { return PropVal; } // Get the value
set { PropVal = value; } // Set the value
}
}
然后,您可以内实现任意数量的属性您公共类,这样客户端可以设置/获取与索引,描述符,安全密钥,或什么的,像这样的属性:
public class ParameterizedProperties
{
// Parameterized properties
private Property<int> m_IntProp = new Property<int>();
private Property<string> m_StringProp = new Property<string>();
// Parameterized int property accessor for client access
// (ex: ParameterizedProperties.PublicIntProp[index])
public Property<int> PublicIntProp
{
get { return m_IntProp; }
}
// Parameterized string property accessor
// (ex: ParameterizedProperties.PublicStringProp[index])
public Property<string> PublicStringProp
{
get { return m_StringProp; }
}
}
最后,客户端代码将访问你这样的公共类的“参数”属性:
ParameterizedProperties parmProperties = new ParameterizedProperties();
parmProperties.PublicIntProp[1] = 100;
parmProperties.PublicStringProp[1] = "whatever";
int ival = parmProperties.PublicIntProp[1];
string strVal = parmProperties.PublicStringProp[1];
当然,这看起来很奇怪,但它绝对有诀窍。此外,从客户端代码的角度来看,这并不奇怪 - 它简单直观,并且像真正的属性一样行事。它不会破坏任何C#规则,也不会与其他.NET托管语言不兼容。从类实现者的角度来看,创建一个可重用的通用“参数化”属性模板类使组件编码变得相对轻而易举,如此处所示。
注意:您始终可以覆盖通用属性类以提供自定义处理,如索引查找,安全控制的属性访问或任何你想要的。
干杯!
马克琼斯
好的答案男人。不知道你为什么建议使用“”而不是String.Empty,尽管......原来对我来说似乎更加明确。 – Stimul8d 2009-09-04 09:20:10
@ Stimul8d:我不关注。 ``“`不明确?我在两者之间看到的唯一区别(也就是说,恕我直言,一个程序员*应该看到)是`String.Empty`是六倍的长度,因此它需要六倍的空间并且需要六倍的时间来阅读。它使代码变坏了六倍。作为比较,就好像我们将使用`Int32.Zero`而不是`0`。 – 2009-09-04 09:54:04
鼻子独角兽:我上星期只是用同样的说法! – 2010-04-06 13:35:43