您忽略了解释问题的第三个选项:
//1
TestClass a = "This works fine.";
//2
ITestInterface i = "This doesn't work either!";
//3
DoSomething("Why doesn't this work?");
在
(1)中,您声明了
TestClass a
。这意味着编译器知道当您使用不同类型(在本例中为字符串)时,它应该尝试将该值转换为
TestClass
。
在
(2)中,您声明了
ITestInterface i
。这意味着编译器知道当您使用不同类型(在本例中为字符串)时,它应该尝试将该值转换为
ITestInterface
。
这就是问题的根源。在
string
和
ITestInterface
之间没有定义转换。
您目前正在考虑的是:
好吧,我知道我想要将其转换为TestClass
。为什么编译器不能弄清楚我想要做什么?
简短的答案是
编译器拒绝猜测。
您想要发生的事情会导致不可能的情况。例如,如果有第二个类也实现了
ITestInterface
,会发生什么?
class SecondTestClass: ITestInterface
{
public static implicit operator SecondTestClass(string url)
{
return new SecondTestClass(url);
}
public SecondTestClass(string url)
{
Value = GetValueFromTheInternet(url);
}
public string Value { get; set; }
}
让我们重新评估您的代码:
//1
TestClass a = "This works fine."
这是有效的。从 string
转换为 TestClass
。
//2
SecondTestClass b = "This works fine."
这个代码有效。它将 string
转换为 SecondTestClass
。
//3
ITestInterface i = "This still doesn't work!";
//4
DoSomething("This doesn't work for the same reason as //3");
这个无法工作。编译器不支持将“string”转换为“ITestInterface”的任何已知转换方式。
编译器无法确定您是否希望将其转换为“TestClass”,然后将其分配给“i”,还是希望将其转换为“SecondTestClass”,然后将其分配给“i”。
正如我之前所说,编译器拒绝猜测。
此外,仅为了明确起见,以下内容可以工作:
TestClass a = "This works fine.";
ITestInterface i1 = a;
DoSomething(a);
DoSomething(i1);
SecondTestClass b = "This works fine.";
ITestInterface i2 = b;
DoSomething(b);
DoSomething(i2);
所有这些赋值都有效。
问题的关键是编译器希望您明确地声明要将字符串转换为哪种类型。在您自己的示例中,您已经明确要求一个TestClass
。请注意,如果您使用了var
,那么这不起作用,因为编译器在这种情况下也无法解决它。
TestClass a = new TestClass("This works fine.");
这段代码有什么问题吗?在我看来,它更加用户友好。 - LiamDocument(params IPart[] parts)
的构造函数创建文档。我正在尝试使其易于包含混合了其他类型内容的“string”块。 - Bradley Uffner