针对您的问题的更通用、更安全和可重用的解决方案可能是实现一个通用的“参数化”属性类,如下所示:
// 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 托管语言不兼容。从类实现者的角度来看,创建一个可重用、通用、“参数化”的属性模板类使得组件编码变得相对容易,如下所示。
注意:您始终可以覆盖通用属性类以提供自定义处理,例如索引查找、安全控制的属性访问或您想要的任何东西。
干杯!
马克琼斯