Cast from Generic type
אחד הדברים המפריעים בעבודה עם Generic Type, שאי אפשר לעשות להם casting לאובייקטים אחרים, לדוגמא:
static void MyFunc<T>(T item)
{
Work((Entity)item);
}
static void Work(Entity item)
{
}
הקוד הא יזרוק שגיאה של:
Cannot convert type 'T' to 'ConsoleApplication1.Entity'
כדי לבצע בכל זאת המרה בין האובייקטים ניתן להשתמש ב - Convert.ChnageType בצורה הבאה:
static void MyFunc<T>(T item)
{
Work((Entity)Convert.ChangeType(item, typeof(Entity)));
}
כדי לחסוך קצת זמן ולכתוב קוד בצורה יפה יותר, כתבתי את ה - Extension Method הבא
public static class ObjectExtension
{
public static T ChangeType<T>(this object obj)
{
return (T)Convert.ChangeType(obj, typeof(T));
}
}
וכעת ניתן לכתוב קוד כזה:
static void MyFunc<T>(T item)
{
Work(item.ChangeType<Entity>());
}