泛型类型从字符串转换 [英] Generic type conversion FROM string

查看:149
本文介绍了泛型类型从字符串转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想用它来存储属性另一个类的类。这些属性只是有一个名字和一个值。理想情况下,我想是可以添加的键入的性质,使价值返回始终是我希望它成为的类型。

I have a class that I want to use to store "properties" for another class. These properties simply have a name and a value. Ideally, what I would like is to be able to add typed properties, so that the "value" returned is always of the type that I want it to be.

该类型应该永远是一个原始。这个类的子类的抽象类基本上存储的名称和值的字符串。这个想法是,这个子类会增加一些类型安全的基类(以及节省我一些转换)。

The type should always be a primitive. This class subclasses an abstract class which basically stores the name and value as string. The idea being that this subclass will add some type-safety to the base class (as well as saving me on some conversion).

所以,我创建了一个类,这是(大约)这样的:

So, I have created a class which is (roughly) this:

public class TypedProperty<DataType> : Property
{
    public DataType TypedValue
    {
        get { // Having problems here! }
        set { base.Value = value.ToString();}
    }
}

所以,问题是:

是否有通用的方式来从字符串转换回原始?

我似乎无法找到任何通用的接口,全线链接转换(类似的 ITryParsable 的本来的理想!)。

I can't seem to find any generic interface that links the conversion across the board (something like ITryParsable would have been ideal!).

推荐答案

我不知道我是否正确地理解你的意图,但让我们看看这个帮助。

I am not sure whether I understood your intentions correctly, but let's see if this one helps.

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();}
    }
}

这篇关于泛型类型从字符串转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆