将隐式转换为具体类型的结果存储到接口中失败
Storing the result of an implicit cast to a concrete type into an interface fails
我想将实现隐式转换为接口。我知道 C# 规范不允许这样做,这对我的用例来说很好。
但是当我隐式转换为实现该接口的类型时,我无法将它存储在该接口的变量中。这让我感到惊讶。
这些是定义:
public interface ISomeInterface
{
}
public class SomeImplementation : ISomeInterface
{
}
public class Class1
{
public static implicit operator SomeImplementation(Class1 class1)
{
return new SomeImplementation();
}
}
var class1 = new Class1();
// Works
SomeImplementation s1 = class1;
// Works
ISomeInterface i1 = s1;
// This is what I want to do
ISomeInterface i2 = class1;
// Cannot implicitly convert type 'Class1' to 'ISomeInterface'.
// An explicit conversion exists (are you missing a cast?)
我希望它能编译,因为可以将 Class1
隐式转换为 SomeImplementation
并且 SomeImplementation
实现 ISomeInterface
.
为什么不允许这样做?
"Well, in short, that there is no technical reason why the own conversions from / to interfaces are not allowed. The reason is because they open the door to certain scenarios that the language designers did not want to open and for that reason they prohibited them." - 有关详细信息,请参阅 Conversions (explicit or implicit) and interfaces in C#
我想将实现隐式转换为接口。我知道 C# 规范不允许这样做,这对我的用例来说很好。
但是当我隐式转换为实现该接口的类型时,我无法将它存储在该接口的变量中。这让我感到惊讶。
这些是定义:
public interface ISomeInterface
{
}
public class SomeImplementation : ISomeInterface
{
}
public class Class1
{
public static implicit operator SomeImplementation(Class1 class1)
{
return new SomeImplementation();
}
}
var class1 = new Class1();
// Works
SomeImplementation s1 = class1;
// Works
ISomeInterface i1 = s1;
// This is what I want to do
ISomeInterface i2 = class1;
// Cannot implicitly convert type 'Class1' to 'ISomeInterface'.
// An explicit conversion exists (are you missing a cast?)
我希望它能编译,因为可以将 Class1
隐式转换为 SomeImplementation
并且 SomeImplementation
实现 ISomeInterface
.
为什么不允许这样做?
"Well, in short, that there is no technical reason why the own conversions from / to interfaces are not allowed. The reason is because they open the door to certain scenarios that the language designers did not want to open and for that reason they prohibited them." - 有关详细信息,请参阅 Conversions (explicit or implicit) and interfaces in C#