我有一个存储的序列化值和类型的类。我想有一个属性/方法返回已浇铸的值:
I have a class that stores a serialized value and a type. I want to have a property/method returning the value already casted:
public String Value { get; set; }
public Type TheType { get; set; }
public typeof(TheType) CastedValue { get { return Convert.ChangeType(Value, typeof(_Type)); }
这是可能在C#?
Is this possible in C#?
这是可能的,如果包含该属性的类是通用的,您声明使用泛型参数属性:
It's possible if the class containing the property is generic, and you declare the property using the generic parameter:
class Foo<TValue> {
public string Value { get; set; }
public TValue TypedValue {
get {
return (TValue)Convert.ChangeType(Value, tyepof(TValue));
}
}
}
另一种方法是使用一个通用的方法来代替:
An alternative would be to use a generic method instead:
class Foo {
public string Value { get; set; }
public Type TheType { get; set; }
public T CastValue<T>() {
return (T)Convert.ChangeType(Value, typeof(T));
}
}
您也可以使用 System.ComponentModel.TypeConverter
类进行转换,因为它们允许一个类来定义它自己的转换器。
You can also use the System.ComponentModel.TypeConverter
classes to convert, since they allow a class to define it's own converter.
修改:请注意,调用泛型方法时,必须指定泛型类型参数,因为编译器无法推断它:
Edit: note that when calling the generic method, you must specify the generic type parameter, since the compiler has no way to infer it:
Foo foo = new Foo();
foo.Value = "100";
foo.Type = typeof(int);
int c = foo.CastValue<int>();
您必须知道在编译时的类型。如果你不知道在编译时的类型,那么你必须将其存储在一个对象
,在这种情况下,你可以添加以下属性到富
类:
You have to know the type at compile time. If you don't know the type at compile time then you must be storing it in an object
, in which case you can add the following property to the Foo
class:
public object ConvertedValue {
get {
return Convert.ChangeType(Value, Type);
}
}