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

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

问题描述

我有一个类,我想用它来存储另一个类的属性".这些属性只有一个名称和一个值.理想情况下,我想要的是能够添加 typed 属性,以便返回的值"始终是我想要的类型.

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

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

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