开发者

How to set a struct value T from Type

I'm using the extension from Joel's string-to-nullable-type answer here:

public static Nullable<T> ToNullable<T>(this string s) where T: struct
{
    Nullable<T> result = new Nullable<T>();
    try
    {
        if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0)
        {
            TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
            result = (T)conv.ConvertFrom(s);
        }
    }
    catch { } 
    return result;
}

And in my code, I've got the data开发者_运维技巧 from a Type. Is there a way to cast or use that extension using Type?

UPDATE 1:

var values = from p in xdoc.Descendents("Answers")
         select r.Attribute("Value").Value.ToNullable<Type.GetType(r.DataType)>()

r.DaraType is a data string.


No you can't specify a generic type argument to be the result of a method call that returns a Type object.

i.e. this is invalid ToNullable<Type.GetType(r.DataType)>()

The type needs to be evaluated at compile time and if your syntax was valid the compiler could not tell what the type was in result of your linq query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜