开发者

Reference inherited class's <T>ype in a derived class

开发者 https://www.devze.com 2022-12-23 04:03 出处:网络
I don\'t know if its possible or not, but here\'s what I need. I\'m toying around with something and want to know if its possible since you can\'t create your own data type based on a sealed type such

I don't know if its possible or not, but here's what I need. I'm toying around with something and want to know if its possible since you can't create your own data type based on a sealed type such as int, Int32, Int64, etc.

I want to create a top-level class that is defined of a given type with some common stuff. Then, derive this into two subclasses, but in this case, each class is based on either and int or Int64 type. From THAT instance, create an instance of either one and know its yped basis for parameter referenc / return settings.

So when I need to create an i开发者_Go百科nstance of the "ThisClass", I don't have to know its type basis of either int or Int64, yet IT will know the type and be able to allow methods/functions to be called with the typed... This way, If I want to change my ThisClass definition from SubLevel1 to SubLevel2, I don't have to dance around all different data type definitions.

Hope this makes sense..

public class TopLevel<T>
{
    ... 
}

public class SubLevel1 : TopLevel<int>
{
    ...
}

public class SubLevel2 : TopLevel<Int64>
{ 
    ...
}

public class ThisClass : SubLevel1
{
    ...
    public <based on the Int data type from SubLevel1> SomeFunc()
    {  
        return <the Int value computed>;
    }
}


I assume SomeFunc should be present in all subclasses of TopLevel<T> so you should define it there:

public abstract class TopLevel<T>
{
    public TopLevel()
    {
    }

    public abstract T SomeFunc();
}

and specific subclasses will know the generic type parameter, so ThisClass would define SomeFunc as:

public class ThisClass : SubLevel1
{ ...
   public override int SomeFunc()
   {  
      return <the Int value computed>;
   }
}


That can't be done at compile time without paramterizing all of the derived classes :

public class ThisClass<T> : SubLevel1<T> etc etc

You could do it at runtime with reflection by inspecting typeof(ThisClass).BaseType etc. but that could get pretty messy as you need to write code that understands the inheritance and generic type parameter hierarchy of the entire base class trunk.


You cannot do this as asked.

However, you can write using MyType = System.Int32; at the top of the file, then use MyType everywhere in the file. This will allow you to change types easily.

0

精彩评论

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

关注公众号