在派生类中引用继承类的类型
我不知道这是否可能,但这就是我需要的。 我正在尝试一些东西,想知道它是否可能,因为您无法基于密封类型(例如 int、Int32、Int64 等)创建自己的数据类型。
我想创建一个顶级类,它是用一些常见的东西定义给定类型。然后,将其派生为两个子类,但在本例中,每个类都基于 int 或 Int64 类型。从该实例中,创建任一实例并了解其参数引用/返回设置的类型基础。
因此,当我需要创建“ThisClass”的实例时,我不必知道其 int 或 Int64 的类型基础,但 IT 将知道该类型并能够允许使用类型化的方法/函数来调用...这样,如果我想将 ThisClass 定义从 SubLevel1 更改为 SubLevel2,我不必围绕所有不同的数据类型定义。
希望这是有道理的..
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 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 instance 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>;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设 SomeFunc 应该出现在
TopLevel
的所有子类中,因此您应该在那里定义它:并且特定子类将知道通用类型参数,因此 ThisClass 会将 SomeFunc 定义为:
I assume SomeFunc should be present in all subclasses of
TopLevel<T>
so you should define it there:and specific subclasses will know the generic type parameter, so ThisClass would define SomeFunc as:
如果不参数化所有派生类,则无法在编译时完成:
您可以通过检查
typeof(ThisClass).BaseType
等在运行时通过反射来完成此操作,但这可能会变得非常混乱需要编写能够理解整个基类主干的继承和泛型类型参数层次结构的代码。That can't be done at compile time without paramterizing all of the derived classes :
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.您不能按照要求执行此操作。
但是,您可以在文件顶部写入
using MyType = System.Int32;
,然后在文件中的任何位置使用MyType
。这将允许您轻松更改类型。You cannot do this as asked.
However, you can write
using MyType = System.Int32;
at the top of the file, then useMyType
everywhere in the file. This will allow you to change types easily.