案例是我有以下类,例如:
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));
我的问题是如何在不在代码中创建“if”分支的情况下以干净的方式解决这个问题?喜欢以下内容:
SendFile sendFile;
if(String.IsNullOrEmpty(address))
{
sendFile = new SendFile(id);
}
else
{
sendFile = new SendFile(new Uri(address));
}
最佳答案
在您上面的版本中,您得到以下编译错误:
Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'System.Uri'
阅读时MSDN documentation它指出:
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
因为 string
和 Uri
之间没有隐式转换(你也不希望这样,就好像你有两个不同的构造函数一样......),
要使用条件运算符,您应该做一些不同的事情:
var sendFile = String.IsNullOrEmpty(address) ? new SendFile(id) :
new SendFile(new Uri(address));
关于c# - 重载中的 Resolve 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46116585/