在 C# 中,有没有办法在构造函数中引用调用类?

问题描述 投票:0回答:3

我正在用 C# 为一个类创建一个构造函数,我希望它根据调用它的类的类型以不同方式填充它的值。 比如有一个班叫

Employer
,还有一个班叫
Person
。 当
Employer
的实例调用
new Person();
时,我希望
Person
中的构造函数将新人的
Employed
变量设置为
true
。 这在 C# 中可能吗?

尝试寻找答案,但不确定如何表达问题。

更新:正如有用的评论所回答的那样,类或函数似乎不可能直接访问其调用者而不明确地向其提供引用。

起初我觉得构造器并没有完全解决我最初的需求,但是把这些写出来帮助我理解了他们是如何做到的:

public class Person
{
    bool employed = false;

    void setDefaultValues()
    {
        //do stuff
    }

    public Person()//empty constructor
    {
        setDefaultValues();
    }

    public Person(Employer em) //type-safe constructor
    {
        setDefaultValues();
        employed = true;
    }

    public Person(Type ty) //adaptable constructor
    {
        setDefaultValues();
        if (ty == typeOf(Employer))
        {
            employed = true;
        }
    }

}
public class Employer
{
//This person will not be employed
    Person nonemployee = new Person();

//This person will be employed, via type-safe constructor
    Person employee1 = new Person(this);

//This person will be employed, via adaptable constructor
    Person employee2 = new Person(this.GetType);
}
c# .net
3个回答
4
投票

你不能自动完成,不。 (你可以获取堆栈跟踪并解析它,但面对 JIT 编译器优化等它会非常脆弱)我认为这样做也会使代码脆弱且难以维护 - 效果就像“远处的幽灵般的动作”。

最简单的选择是在构造函数中添加一个

bool employed
参数。那么在每个调用站点上,您希望构造的对象的行为方式真的很明显。


3
投票

有几种不同的方法可以做到这一点。首先是重载构造函数。

public Person() {
   this.Employed = false;
}
public Person(bool employed) {
   this.Employed = employed;
}

想到的第二个是在实例化对象时填充期望值。

Person myPerson = new Person {Employed = true };

0
投票

你可以有

multiple constructors
一个班级的不同输入:

public Person() {
   this.Employed = false;
}
public Person(bool employed) {
   this.Employed = employed;
}
public Person(bool employed,bool _isEmploye) {
    if(_isEmploye)
        this.Employed = true;
    else
        this.Employed = false;
}

并在任何地方使用适当的输入:

Person p = new Person(true,true);
© www.soinside.com 2019 - 2024. All rights reserved.