Reputation: 19903
The code below add some object in MemoryCache
. These objects can have different type.
I'd like a method able to return the object from MemoryCache
but the return type can be different.
In my sample it's 2 but can be much more. In my sample, the type return are IT1
or List<IT2>
How can I implement this method ?
I'd like method like this (the type returned can be different depending the key) :
public ??? GetObjectFromKey(string key)
{
return _cache.Get(key);
}
Thanks,
MemoryCache _cache = MemoryCache.Default;
var it1 = new T1 { Name = "My" };
var it2 = new List<IT2>().Add(new T2 { Age = 5 });
_cache.Add("ITC1", it1, new CacheItemPolicy());
_cache.Add("ITC2", it2, new CacheItemPolicy());
var typeName = _cache.Get("ITC1").GetType();
public interface IT1
{
string Name { get; set; }
}
public class T1 : IT1
{
public string Name { get; set; }
}
public class T2 : IT2
{
public int Age { get; set; }
}
public interface IT2
{
int Age { get; set; }
}
Upvotes: 0
Views: 93
Reputation: 2802
If you know the type when you are calling the GetObjectFromKey you can use generics:
public T GetObjectFromKey(string key)
{
object returnObj = _cache.Get(key);
if(returnObj.GetType() == typeof(T)) // may need to also check for inheritance
{
return (T) returnObj;
}
else
{
throw new Expcetion("InvalidType");
}
}
Then when you call it:
IT1 myObj = GetObjectFromKey<IT1>("mykey");
As promised, here is how you can construct the generic method from an arbitrary type at run time (though I don't see how this is going to help!):
Type t = typeof(Something); // your type at run time
Type cacheType = _cache.GetType(); // The type that has the GetObjectFromKeyMethod
MethodInfo lGenericMethod = cacheType.GetMethod("GetObjectFromKey");
MethodInfo lTypedMethod = lMethod.MakeGenericMethod(t);
dynamic lReturn = lTypedMethod.Invoke(_cache, new object[] { "mykey" } );
Though clearly you can't do anything with lReturn
as you don't know the type at compile time and you could have just returned an object (or else some common interface) and called GetType
on that. Still, it is fun to write fun reflection methods like that :P
Upvotes: 0
Reputation: 1038850
Generics?
public T GetObjectFromKey<T>(string key)
{
return (T)_cache.Get(key);
}
Upvotes: 0
Reputation: 174329
The return type of your cache has to be either object
or dynamic
. You have no other possibility, because the classes you put into your cache have nothing in common.
Upvotes: 1