C# 重载中的解析函数

C# 重载中的解析函数,c#,overloading,C#,Overloading,例如,我有以下类别: public class SendFile { public SendFile(Uri uri) { /* some code here */ } public SendFile(string id) { /* some code here */ } } 然后,我们知道如果我想解析构造函数,我不能像下面这样做: // some string defined which are called "address" and "id" var sendFile

例如,我有以下类别:

public class SendFile
{
     public SendFile(Uri uri) { /* some code here */ }
     public SendFile(string id) { /* some code here */ }
}
然后,我们知道如果我想解析构造函数,我不能像下面这样做:

// some string defined which are called "address" and "id"
var sendFile = new SendFile(String.IsNullOrEmpty(address) ? id : new Uri(address));
SendFile sendFile;
if(String.IsNullOrEmpty(address))
{
     sendFile = new SendFile(id);
}
else
{
     sendFile = new SendFile(new Uri(address));
}
我的问题是如何以干净的方式解决这个问题,而不在代码中创建“if”分支?他喜欢以下几点:

// some string defined which are called "address" and "id"
var sendFile = new SendFile(String.IsNullOrEmpty(address) ? id : new Uri(address));
SendFile sendFile;
if(String.IsNullOrEmpty(address))
{
     sendFile = new SendFile(id);
}
else
{
     sendFile = new SendFile(new Uri(address));
}

在上面的版本中,您会得到以下编译错误:

无法确定条件表达式的类型,因为“string”和“System.Uri”之间没有隐式转换

在阅读时,它指出:

第一个_表达式和第二个_表达式的类型必须相同,或者必须存在从一种类型到另一种类型的隐式转换


由于
string
Uri
彼此之间没有隐式转换(您也不希望这样做,就像您不希望这样,为什么有两个不同的构造函数..), 要使用条件运算符,您应该稍微不同:

var sendFile = String.IsNullOrEmpty(address) ? new SendFile(id) : 
                                               new SendFile(new Uri(address));

一个选项可能是将一个
静态
“工厂”方法添加到
发送文件
,并在那里处理它:

public class SendFile
{
    public SendFile(Uri uri) { /* some code here */ }
    public SendFile(string id) { /* some code here */ }

    public static SendFile Create(string url, string fallbackId = null)
    {
        return string.IsNullOrEmpty(url)
            ? new SendFile(fallbackId)
            : new SendFile(new Uri(url));
    }
}

参数命名应明确指出,
fallbackId
仅在未提供
url
的情况下使用。

请参阅关于设计模式的链接我确实需要修复编译错误:
var sendFile=new sendFile(String.IsNullOrEmpty(address)?(动态)id:new Uri(address))。但事实上,不要用这个:)吉拉德提出了一种更清洁的解决方案。