[英]Generic type conversion FROM string
我有一个类,我想用它来存储另一个类的“属性”。 这些属性只有一个名称和一个值。 理想情况下,我希望能够添加类型化属性,以便返回的“值”始终是我想要的类型。
类型应该始终是原始类型。 这个类是一个抽象类的子类,它基本上将名称和值存储为字符串。 这个想法是这个子类将为基类添加一些类型安全(以及节省我的一些转换)。
所以,我创建了一个类,它(大致)是这样的:
public class TypedProperty<DataType> : Property
{
public DataType TypedValue
{
get { // Having problems here! }
set { base.Value = value.ToString();}
}
}
所以问题是:
有没有一种“通用”的方法可以将字符串转换回原语?
我似乎找不到任何可以全面链接转换的通用接口(像ItryParsable这样的东西本来是理想的!)。
我不确定我是否正确理解了您的意图,但让我们看看这是否有帮助。
public class TypedProperty<T> : Property where T : IConvertible
{
public T TypedValue
{
get { return (T)Convert.ChangeType(base.Value, typeof(T)); }
set { base.Value = value.ToString();}
}
}
lubos hasko 的方法对于 nullables 失败。 下面的方法适用于可空值。 不过我没有想出来。 我是通过谷歌找到的: http ://web.archive.org/web/20101214042641/http://dogaoztuzun.com/post/C-Generic-Type-Conversion.aspx 感谢“Tuna Toksoz”
先用:
TConverter.ChangeType<T>(StringValue);
课程如下。
public static class TConverter
{
public static T ChangeType<T>(object value)
{
return (T)ChangeType(typeof(T), value);
}
public static object ChangeType(Type t, object value)
{
TypeConverter tc = TypeDescriptor.GetConverter(t);
return tc.ConvertFrom(value);
}
public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter
{
TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
}
}
对于许多类型(整数、双精度、日期时间等),有一个静态 Parse 方法。 您可以使用反射调用它:
MethodInfo m = typeof(T).GetMethod("Parse", new Type[] { typeof(string) } );
if (m != null)
{
return m.Invoke(null, new object[] { base.Value });
}
TypeDescriptor.GetConverter(PropertyObject).ConvertFrom(Value)
TypeDescriptor
是具有方法GetConvertor
类,它接受一个Type
对象,然后您可以调用ConvertFrom
方法来转换该指定对象的value
。
受Bob回答的启发,这些扩展还支持空值转换和所有原语来回转换。
public static class ConversionExtensions
{
public static object Convert(this object value, Type t)
{
Type underlyingType = Nullable.GetUnderlyingType(t);
if (underlyingType != null && value == null)
{
return null;
}
Type basetype = underlyingType == null ? t : underlyingType;
return System.Convert.ChangeType(value, basetype);
}
public static T Convert<T>(this object value)
{
return (T)value.Convert(typeof(T));
}
}
例子
string stringValue = null;
int? intResult = stringValue.Convert<int?>();
int? intValue = null;
var strResult = intValue.Convert<string>();
检查静态Nullable.GetUnderlyingType
。 - 如果底层类型为 null,则模板参数不是Nullable
,我们可以直接使用该类型 - 如果底层类型不为 null,则在转换中使用底层类型。
似乎对我有用:
public object Get( string _toparse, Type _t )
{
// Test for Nullable<T> and return the base type instead:
Type undertype = Nullable.GetUnderlyingType(_t);
Type basetype = undertype == null ? _t : undertype;
return Convert.ChangeType(_toparse, basetype);
}
public T Get<T>(string _key)
{
return (T)Get(_key, typeof(T));
}
public void test()
{
int x = Get<int>("14");
int? nx = Get<Nullable<int>>("14");
}
您可能会使用诸如traits class 之类的构造。 通过这种方式,您将拥有一个参数化的辅助类,该类知道如何将字符串转换为其自身类型的值。 那么你的 getter 可能看起来像这样:
get { return StringConverter<DataType>.FromString(base.Value); }
现在,我必须指出,我对参数化类型的经验仅限于 C++ 及其模板,但我想有一些方法可以使用 C# 泛型来做同样的事情。
我使用了 lobos 答案并且它有效。 但是由于文化设置,我在转换双打时遇到了问题。 所以我加了
return (T)Convert.ChangeType(base.Value, typeof(T), CultureInfo.InvariantCulture);
public class TypedProperty<T> : Property
{
public T TypedValue
{
get { return (T)(object)base.Value; }
set { base.Value = value.ToString();}
}
}
我使用通过对象进行转换。 它稍微简单一点。
又一个变种。 处理空值,以及字符串为空且 T不可空的情况。
public class TypedProperty<T> : Property where T : IConvertible
{
public T TypedValue
{
get
{
if (base.Value == null) return default(T);
var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
return (T)Convert.ChangeType(base.Value, type);
}
set { base.Value = value.ToString(); }
}
}
您可以在一行中完成,如下所示:
YourClass obj = (YourClass)Convert.ChangeType(YourValue, typeof(YourClass));
快乐编码;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.