将当前对象类型传递给基础构造函数调用 [英] Pass current object type into base constructor call

查看:84
本文介绍了将当前对象类型传递给基础构造函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取继承类的类型并将其传递给继承的类的基础构造函数?请参阅下面的代码示例:

How do I grab the Type of the inherited class and pass it into the base constructor of the class also inherited? See the code sample below:

// VeryBaseClass is in an external assembly
public abstract class VeryBaseClass
{
    public VeryBaseClass(string className, MyObject myObject)
    {

    }
}

// BaseClass and InheritedClass are in my assembly
public abstract class BaseClass : VeryBaseClass
{
    public BaseClass(MyObject myObject) :
        base(this.GetType().Name, myObject) // can't reference "this" (Type expected)
    {

    }
}

public class InheritedClass : BaseClass
{
    public InheritedClass(MyObject myObject)
    {

    }
}

base(typeof(this).Name,myObject)不起作用,因为我无法引用但是,由于对象尚未完成构建,因此不存在。

The line base(typeof(this).Name, myObject) doesn't work because I can't reference this yet, as the object hasn't finished constructing and therefore doesn't exist.

是否可以获取类型目前构造对象?

Is it possible to grab the Type of the currently constructing object?

编辑:

将样本更正为 orsogufo建议,但仍然不起作用,因为 this 未定义。

Corrected the sample as orsogufo suggested, but still doesn't work, as this is undefined.

编辑2:

为了澄清,我想结束使用InheritedClass传递到 VeryBaseClass(s​​tring className,MyObject myObject)构造函数。

Just to clarify, I want to end up with "InheritedClass" being passed into the VeryBaseClass(string className, MyObject myObject) constructor.

推荐答案

啊哈!我找到了解决方案。您可以使用泛型来执行此操作:

Ah Hah! I found a solution. You can do it with generics:

public abstract class VeryBaseClass
{
    public VeryBaseClass(string className, MyObject myObject)
    {
        this.ClassName = className;
    }

    public string ClassName{ get; set; }
}
public abstract class BaseClass<T> : VeryBaseClass
{
    public BaseClass(MyObject myObject)
        : base(typeof(T).Name, myObject)
    {
    }
}

public class InheritedClass : BaseClass<InheritedClass>
{
    public InheritedClass(MyObject myObject) 
        : base(myObject)
    {

    }
}

这篇关于将当前对象类型传递给基础构造函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆