45

c# – 具有相同参数类型的构造函数

 5 years ago
source link: https://codeday.me/bug/20190112/511053.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

我有一个带有两个构造函数的Person对象 – 一个接受一个int(personId),另一个接受一个字符串(logonName).我想要另一个带字符串的构造函数(badgeNumber).我知道这不可能做到,但似乎这可能是一种常见的情况.有一种优雅的方式处理这个?我想这适用于任何重载方法.码:

public class Person
{
    public Person() {}

    public Person(int personId)
    {
        this.Load(personId);
    }

    public Person(string logonName)
    {
        this.Load(logonName);
    }

    public Person(string badgeNumber)
    {
        //load logic here...
    }

…等等.

您可以考虑使用自定义类型.

例如,创建LogonName和BadgeNumber类.

然后你的函数声明看起来像……

public Person(LogonName ln)
{
    this.Load(ln.ToString());
}

public Person(BadgeNumber bn)
{
    //load logic here...
}

这样的解决方案可能会为您提供一个保持管理这些字符串的格式和用法的业务逻辑的好地方.

翻译自:https://stackoverflow.com/questions/31215/constructors-with-the-same-argument-type


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK