المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Do special processing for a type in a generic class



C# Programming
07-14-2009, 10:51 PM
I'm trying to roll up some old (originally .net 1.1) abstract classes into generics. The classes in question all provide similar functionality for a data object of a specific type. For the most part things are going well, but I've ran into a few places where one one of the data objects is of a type that needs extra processing in one method beyond what all the other types need. I can check the type of T to see if it's the type I need to do the special processing for, but the cast from T to SpecialType won't compile. Is there a different way I can do this, or is what I want to do impossible?



class MyGenericClass : ICloneable where T: class, new()
{

private T m_storedClass;
...

private DoStuff()
{
//do stuff for all types

//objects of SpecialType need extra stuff done.
if (typeof(T) == typeof(SpecialType))
{
//compiler error: Error Cannot convert type 'T' to 'SpecialType'
((SpecialType)m_storedClass).SpecialString = "foo";
}
}

The European Way of War: Blow your own continent up.
The American Way of War: Go over and help them.