Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an interface for a creaky property-map:

interface IPropertyMap
{
   bool Exists(string key);
   int GetInt(string key);
   string GetString(string key);
   //etc..
}

I want to create an extension method like so:

public static T GetOrDefault<T>(this IPropertyMap map, string key, T defaultValue)
{
    if (!map.Exists(key))
        return defaultValue;
    else
    {
        if (typeof(T) == typeof(int)) return (T)map.GetInt(key);
        //etc..
    }
}

But the compiler won't let me cast to T. I tried adding where T : struct but that doesn't seem to help.

What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
260 views
Welcome To Ask or Share your Answers For Others

1 Answer

I believe this is because the compiler doesn't know what type of operation it needs to perform. IIRC, you can get it to work if you introduce boxing:

if (typeof(T) == typeof(int)) return (T)(object)map.GetInt(key);

but that's not ideal in terms of performance.

I think it's just a limitation of generics, unfortunately.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...