c# - 重载中的 Resolve 函数

标签 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 = 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.


因为 stringUri 之间没有隐式转换(你也不希望这样,就好像你有两个不同的构造函数一样......), 要使用条件运算符,您应该做一些不同的事情:

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

关于c# - 重载中的 Resolve 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46116585/

相关文章:

c# - asp.net核心和asp-route-id

c# - C#如何将一个程序编译成不同的项目

c# - 为什么 DevExpress Treelist 会定期抛出 HideException?

c# - 在执行时使用 MVC 3 和 jQuery Validator 添加验证

rust - 如何编写支持+=操作的特征绑定(bind),其右手是Rust中复杂情况下的引用

java - 重载函数 int... 和 long... 同时

c# - 正确的过载选择

c# - 重载和覆盖问题

C++:容器元素的引用

java - 为什么当方法重载时多态性并不重要?