制作通用属性 [英] Making a generic property

查看:32
本文介绍了制作通用属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储序列化值和类型的类.我想要一个属性/方法返回已经转换的值:

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, typeof(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>();

你必须在编译时知道类型.如果您在编译时不知道类型,那么您必须将其存储在 object 中,在这种情况下,您可以将以下属性添加到 Foo 类:

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

这篇关于制作通用属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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