如何从另一个派生类获取派生类的类型

发布于 2024-12-29 21:03:02 字数 568 浏览 1 评论 0原文

我有(伪)代码:

public class GlobalClass
{
    public GlobalClass()
    {
        var x = this.GetType().Name // Returns "Channels"
        // WHAT TO DO HERE?
    }
}

public class BaseClass
{
    public string Title { get; set; }
}

并使用此代码:

public class Channels : GlobalClass
{
    public Channels()
    {

    }

    public class Channel : BaseClass
    {

    }
}

注释所在的位置(// WHAT TO DO HERE?),我想获取 BaseClass 的运行时类型, 我的示例代码中的其中位置应返回 Channel

我对不同的方法持开放态度,但前提是它附有我为什么应该更改代码的解释。

I have the (pseudo) code:

public class GlobalClass
{
    public GlobalClass()
    {
        var x = this.GetType().Name // Returns "Channels"
        // WHAT TO DO HERE?
    }
}

public class BaseClass
{
    public string Title { get; set; }
}

And using this code:

public class Channels : GlobalClass
{
    public Channels()
    {

    }

    public class Channel : BaseClass
    {

    }
}

Where the comment is (// WHAT TO DO HERE?), I want to get the runtime type of BaseClass,
where in my sample code should return Channel.

I am open to different approaches, but only if it's accompanied with an explanation why I should change the code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

所有深爱都是秘密 2025-01-05 21:03:02

我认为你在这里需要一个通用类,例如:

    public class GlobalClass<T> where T : BaseClass
    {
        public GlobalClass()
        {
            var theType = typeof(T);    //you got it
        }
    }
    public class BaseClass
    {
        public string Title { get; set; }
    }

    public class Channel : BaseClass { }
    public class Channels : GlobalClass<Channel> { }

I think you need a generic class here, something like:

    public class GlobalClass<T> where T : BaseClass
    {
        public GlobalClass()
        {
            var theType = typeof(T);    //you got it
        }
    }
    public class BaseClass
    {
        public string Title { get; set; }
    }

    public class Channel : BaseClass { }
    public class Channels : GlobalClass<Channel> { }
樱桃奶球 2025-01-05 21:03:02

您可以像这样使用反射:

using System.Reflection;

...

public class GlobalClass
{
    public GlobalClass()
    {
        Type[] types = Assembly.GetExecutingAssembly ().GetTypes ();
        foreach ( Type t in types )
        {
            if ( t.BaseType == typeof ( BaseClass ) )
            {
                Console.WriteLine ( "I found a class " + t.Name + " that subclass BaseClass" );
            }
        }
    }
}

另请参阅 Stack Overflow 问题程序集中的类列表

You can use reflection like this:

using System.Reflection;

...

public class GlobalClass
{
    public GlobalClass()
    {
        Type[] types = Assembly.GetExecutingAssembly ().GetTypes ();
        foreach ( Type t in types )
        {
            if ( t.BaseType == typeof ( BaseClass ) )
            {
                Console.WriteLine ( "I found a class " + t.Name + " that subclass BaseClass" );
            }
        }
    }
}

See also Stack Overflow question List of classes in an assembly.

云仙小弟 2025-01-05 21:03:02

运算符就是为了这个目的。

getType()方法也可以使用>类型

class Example 
{
    static void ShowTypeInfo (object o) 
    {  
        Console.WriteLine ("type name = {0}, 
                            full type name = {1}", o.GetType(), 
                            o.GetType().FullName ); 
    }

    public static void Main()
    { 
        long longType = 99; 
        Example example= new Example(); 

        ShowTypeInfo (example); 
        ShowTypeInfo (longType); 
    }
}

is operator is just for that purpose.

getType() method with class Type can also be used.

class Example 
{
    static void ShowTypeInfo (object o) 
    {  
        Console.WriteLine ("type name = {0}, 
                            full type name = {1}", o.GetType(), 
                            o.GetType().FullName ); 
    }

    public static void Main()
    { 
        long longType = 99; 
        Example example= new Example(); 

        ShowTypeInfo (example); 
        ShowTypeInfo (longType); 
    }
}
墨小沫ゞ 2025-01-05 21:03:02

要获取任何内容的运行时类型,您首先需要一个对象实例来获取类型。因此,根据您给定的结构,这是不可能的。

有两种可能的方法:

  1. BaseClass 参数添加到 GlobalClass 的构造函数中:

    公共类GlobalClass
    {
        公共全局类(基类数据)
        {
            var dataType = data == null ? null : data.GetType();
            // 对类型做一些事情
        }
    }
    
    公开课频道:GlobalClass
    {
        公共频道(频道数据):基础(数据)
        {
    
        }
    
        公共类通道:BaseClass
        {
    
        }
    }
    
  2. 直接将类型传递给构造函数:

    公共类GlobalClass
    {
        公共 GlobalClass(类型实际类型)
        {
            Debug.Assert(typeof(BaseClass).IsAssignableFrom(actualType));
        }
    }
    
    公开课频道:GlobalClass
    {
        公共频道():基(typeof(频道))
        {
    
        }
    
        公共类通道:BaseClass
        {
    
        }
    }
    

如果由于某种原因结构不允许此处使用泛型(如 Danny Chen 建议),我个人更喜欢第二种方法,因为它不需要实际实例。

To get the runtime type of anything, you first need an object instance to get the type from. So with your given structure, that's not possible.

There are two possible approaches:

  1. Add a BaseClass parameter to the constructor of your GlobalClass:

    public class GlobalClass
    {
        public GlobalClass(BaseClass data)
        {
            var dataType = data == null ? null : data.GetType();
            // do something with the type
        }
    }
    
    public class Channels : GlobalClass
    {
        public Channels(Channel data) : base(data)
        {
    
        }
    
        public class Channel : BaseClass
        {
    
        }
    }
    
  2. Pass the type to the constructor directly:

    public class GlobalClass
    {
        public GlobalClass(Type actualType)
        {
            Debug.Assert(typeof(BaseClass).IsAssignableFrom(actualType));
        }
    }
    
    public class Channels : GlobalClass
    {
        public Channels() : base(typeof(Channel))
        {
    
        }
    
        public class Channel : BaseClass
        {
    
        }
    }
    

If the structure for some reason doesn't allow generics here (as Danny Chen suggested), I'd personally prefer the second approach, since that doesn't need an actual instance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文