至少有两种可能性进行铸造,一种用于类型检查,另一种是两者的组合,称为模式匹配。每个都有其自己的目的,这取决于具体情况:
硬铸 https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/invocation-operator#cast-expression
var myObject = (MyType)source;
如果您绝对确定给定对象是否属于该类型,通常会这样做。如果您订阅了事件处理程序并将发送者对象转换为正确的类型来处理该事件,则使用它的情况。
private void OnButtonClick(object sender, EventArgs e)
{
var button = (Button)sender;
button.Text = "Disabled";
button.Enabled = false;
}
软铸件 https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/as
var myObject = source as MyType;
if (myObject != null)
// Do Something
如果你不知道你是否真的有这种类型,通常会使用它。因此,只需尝试强制转换它,如果不可能,只需返回 null 即可。一个常见的例子是,只有在某个接口被填充时才必须执行某些操作:
var disposable = source as IDisposable;
if(disposable != null)
disposable.Dispose();
还有as
运算符不能用于struct
。这只是因为操作员想要返回一个null
万一演员失败并且struct
永远不可能null
.
类型检查 https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is
var isMyType = source is MyType;
这很少被正确使用。仅当您只需要知道某物是否属于特定类型但不必使用该对象时,此类型检查才有用。
if(source is MyType)
DoSomething();
else
DoSomethingElse();
模式匹配 https://learn.microsoft.com/en-us/dotnet/csharp/pattern-matching
if (source is MyType myType)
DoSomething(myType);
模式匹配是 dotnet 框架中与强制转换相关的最新功能。但您也可以使用以下方法处理更复杂的情况switch语句 https://learn.microsoft.com/en-us/dotnet/csharp/pattern-matching#using-pattern-matching-switch-statements和当子句 https://learn.microsoft.com/en-us/dotnet/csharp/pattern-matching#when-clauses-in-case-expressions:
switch (source)
{
case SpecialType s when s.SpecialValue > 5
DoSomething(s);
case AnotherType a when a.Foo == "Hello"
SomethingElse(a);
}