C# 为什么这种语法在C中有效?
在一个WPF项目中,我得到了一个名为IHavePassword的类,在另一个文件中有一个按钮的侦听器C# 为什么这种语法在C中有效?,c#,C#,在一个WPF项目中,我得到了一个名为IHavePassword的类,在另一个文件中有一个按钮的侦听器 private void DoLogin(object parameter) { if (parameter is IHavePassword passwordContainer) { ... } } 我的问题与is关键字后面的if语句有关,它在那里做什么?是否将方法参数与IHavePassword类新实例进行比较?这样做的目的是让您检查对象是否为IHa
private void DoLogin(object parameter)
{
if (parameter is IHavePassword passwordContainer)
{
...
}
}
我的问题与is关键字后面的if语句有关,它在那里做什么?是否将方法参数与IHavePassword类新实例进行比较?这样做的目的是让您检查对象是否为IHavePassword类型,如果是,您可以在以后使用变量passwordContianer使用它 这称为模式匹配,您可以在此处了解更多信息:
这样做的目的是让您检查对象是否为IHavePassword类型,如果是,您可以在以后使用变量passwordContianer来使用它 这称为模式匹配,您可以在此处了解更多信息:
这称为模式匹配。它是在C7.0中添加的 从文章中: is表达式既测试变量,又将其分配给正确类型的新变量
因此,在您的问题中,变量passwordContainer是为“是真”而预留的变量声明。这称为模式匹配。它是在C7.0中添加的 从文章中: is表达式既测试变量,又将其分配给正确类型的新变量
因此,在您的问题中,变量passwordContainer是为“是真”而预留的变量声明。您问了一个很好的问题,在C语言中有一个称为模式匹配的概念。因此,主要作者试图检查参数coming是否与IHavePassord兼容。如果这是兼容的,那么变量将成为passwordContainer 此microsoft文档链接将有所帮助
希望这有帮助。谢谢你提出的好问题,在C语言中有一个叫做模式匹配的概念。因此,主要作者试图检查参数coming是否与IHavePassord兼容。如果这是兼容的,那么变量将成为passwordContainer 此microsoft文档链接将有所帮助 希望这有帮助。谢谢这应该会有帮助
private void Simple(object parameter)
{
if (parameter is int)
{
//do something which does not need the type
Something();
//this line will not work as it does number not exist, see below SimpleOther
//var newTotal = 1 + number;
//this line does not work as object is not a int
//var newTotal = 1 + parameter;
}
}
private void SimpleOther(object parameter)
{
if (parameter is int number)
{
//this works as it know its type is int and 1 is an int.
var newTotal = 1 + number;
}
}
private void CommonNormalUsage(object parameter)
{
if (parameter is SomeClass someClass)
{
//where SomeClass as a methood called AddSomethingSpecialMethod
someClass.AddSomethingSpecialMethod();
}
//this is done so the runtime knows what type parameter is and con only work
//with an instance which has been "cast" to that type
}
这应该会有所帮助
private void Simple(object parameter)
{
if (parameter is int)
{
//do something which does not need the type
Something();
//this line will not work as it does number not exist, see below SimpleOther
//var newTotal = 1 + number;
//this line does not work as object is not a int
//var newTotal = 1 + parameter;
}
}
private void SimpleOther(object parameter)
{
if (parameter is int number)
{
//this works as it know its type is int and 1 is an int.
var newTotal = 1 + number;
}
}
private void CommonNormalUsage(object parameter)
{
if (parameter is SomeClass someClass)
{
//where SomeClass as a methood called AddSomethingSpecialMethod
someClass.AddSomethingSpecialMethod();
}
//this is done so the runtime knows what type parameter is and con only work
//with an instance which has been "cast" to that type
}
这是。因为语言规范这么说:它检查参数是否是实现IHavePassword的类型的实例,如果是,则提供IHavePassword类型的passwordContainer变量。也就是说。因为语言规范这么说:它检查参数是否是实现IHavePassword并提供passwordContainer的类型的实例IHavePassword类型的变量(如果是)。