开发者

C#: Return T from a dictionary which saves Objects

Is it not ineffective to use for the Dictionary<Type,object> instead of Dictionary<Type,T> ?

Everytime I add an ICustomerService It gets boxed.

If I would have Type,T there should be no boxing, what do you think?

public class MyService
{        
    private static Dictionary<Type, object> _services = new Dictionary<Type, object>();


        public static void AddService<T>(object service)
        {
            if (! (_services.ContainsKey(typeof(T))))
                _services.Add(typeof(T), service);开发者_JAVA技巧
        }


        public static T1 GetService<T1>()
        {
            return (T1) _services[typeof(T1)];
        }
}


Everytime I add an ICustomerService It gets boxed.

That would be highly unusual. Only value type values get boxed. It is technically possible to have a struct implement an interface. But very uncommon to do so. The only overhead you got here is the cast. That's very quick on a reference type and pretty unavoidable by the looks of your snippet.


No, it's not going to get boxed when you add an ICustomerService unless ICustomerService is a value type, which would be unusual. (It sounds like an interface.) Boxing only happens with value types.

Basically you're trying to represent a type relationship which can't be expressed in generics. Boxing for value types (and checks elsewhere) are the only way around this. You can't treat the dictionary as a different type of dictionary for each call, depending on what T is. Generics simply don't work that way. How would you expect the in-memory representation to work under the hood, with a single object (the dictionary) having a different representation for each value (without boxing, somehow)?


Boxing occurs only when you switch between value and reference types.

It means that, in this case, boxing/unboxing occurs only when object is of type int, byte, char, etc.

ICustomerService is an interface (I suppose from naming), so it's a reference type. No boxing occurs.

The GetService method, instead, performs a type casting, which doesn't affect performance until you have a casting operator overriden.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜