我试图寻找这个问题的答案,但找不到太多,很可能是因为我不知道如何正确地寻找它,所以在这里。非常感谢所有帮助。
有了看起来像的基类
abstract public class Property
{
private String name;
public Property(String propertyName)
{
name = propertyName;
}
public String Name
{
get { return name; }
}
abstract public override String ToString();
}
和看起来像的派生类
public class StringProperty : Property
{
private String value; // different properties for different types
public StringProperty(String propertyName, String value) : base(propertyName)
{
this.value = value;
}
public String Value // different signature for different properties
{
get { return value; }
}
public override String ToString()
{
return base.Name + ": " + value;
}
}
在运行时,该函数接收“Property”对象的集合。我需要做什么才能获得每个的“值(value)”?我是否需要一个很大的 if
语句来查询每个“Property”对象的类型?如果没有,是否有更优雅的解决方案?
我试图定义一个要覆盖的抽象“值”属性,但由于返回类型不同,它没有用。我也尝试过隐藏“Value”属性,但我无法让它发挥作用。使用类似 COM 的 Variant 的想法听起来也不太合适。
非常感谢。
编辑:
我应该添加有关我正在尝试做的事情的详细信息。这些属性显示在 Winforms 应用程序中。不同的“TextBox”es 代表不同的属性,并被过滤以进行正确的输入(取决于类型)。更新后的值被读回并存储。容器对象将被序列化为 JSON 并在 Android 和 iPhone 客户端上反序列化,最终这些值将被传递到运行 native C++ 代码的层中,执行 OpenGL 操作。我事先不知道所有需要的属性的种类,所以作为中间人,我想让我的代码尽可能健壮,同时能够为 OpenGL 引擎提供数据。
最佳答案
您可以使用泛型类:
public class AnyProperty<T> : Property
{
private T value;
// ... etc
我真的建议现在让基类成为一个接口(interface):
public interface IProperty
{
public String Name { get; }
}
public class Property<T> : IProperty
{
public Property(String name, T value)
{
Name = name;
Value = value;
}
public String Name { get; private set; }
public T Value { get; private set; }
public override String ToString()
{
return string.Format("{0}: {1}", Name, Value)
}
}
这是示例用法:
var intProp = new Property<int> ("age", 32);
var strProp = new Property<string> ("name", "Earl");
var enumProp = new Property<ColorEnum> ("eye color", ColorEnum.Magenta);
为了使构造更简单,您可以使用工厂方法:
public static Property<T> MakeProperty(string name, T value)
{
return new Property<T>(name,value);
}
var intProp = MakeProperty("age", 32);
var strProp = MakeProperty("name", "Earl");
var enumProp = MakeProperty("eye color", ColorEnum.Magenta);
<子> 不一定推荐,有点OT:
您可以使用扩展方法使其更加有趣:
public static Property<T> AsProp<T>(this T value, string name)
{
return new Property<T>(name,value);
}
var intProp = 32.AsProp("age");
var strProp = "Earl".AsProp("name");
var enumProp = ColorEnum.Magenta.AsProp("eye color");
关于C#:派生类上具有不同返回类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8108012/