我正在通过Josh Smith's CommandSink code显然对C#中的“as”关键字一无所知。
我不明白他为什么写这句话:
IsValid = _fe != null || _fce != null;
因为他只需要写:
IsValid = depObj != null;
既然永远不会出现这种情况,_fe将为null而_fce不为null,反之亦然,对吧?或者我错过了关于“as”如何投射变量的内容?
class CommonElement
{
readonly FrameworkElement _fe;
readonly FrameworkContentElement _fce;
public readonly bool IsValid;
public CommonElement(DependencyObject depObj)
{
_fe = depObj as FrameworkElement;
_fce = depObj as FrameworkContentElement;
IsValid = _fe != null || _fce != null;
}
...
答案是Marc在他的评论中所说的“这是”作为“的全部内容 - 它不会抛出异常 - 它只报告null 。 “
以下是证据:
using System;
namespace TestAs234
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
Employee employee = new Employee();
Person.Test(customer);
Person.Test(employee);
Console.ReadLine();
}
}
class Person
{
public static void Test(object obj)
{
Person person = obj as Customer;
if (person == null)
{
Console.WriteLine("person is null");
}
else
{
Console.WriteLine("person is of type {0}", obj.GetType());
}
}
}
class Customer : Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Employee : Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
答案 0 :(得分:26)
as
将返回您请求的类型的对象。如果不是,则返回null
。如果使用as
并且演员表可能会失败,则需要检查以确保引用有效。
例如,如果depObj的类型为String
,则它不会是null
,但它也无法转换为任何一种请求的类型,并且这两个变量都将变为null
。
答案 1 :(得分:5)
和“施放,如果是”,等同于:
(X is TYPE) ? (TYPE) X : null
is
+ cast
更有效。
depObj可以实现interface,none或两者。
答案 2 :(得分:3)
IsValid = _fe != null || _fce != null;
和
IsValid = depObj != null;
不是相同的测试,因为如果depObj不是FrameworkElement类型,也不是FrameworkContentElement类型但不是null,则第二个测试将返回true,而第一个测试将返回false。
答案 3 :(得分:2)
如果depObj
既不是FrameworkElement
也不是FrameworkContentElement
怎么办?我不知道完整的场景(即类型可能是什么),但这似乎是一种合理的防御策略。
答案 4 :(得分:2)
首先,as
关键字包含is
支票。
if( o is A)
a = (A) o;
与
相同a = o as A;
其次,即使定义了从类型as
到A
的转换运算符,B
也不会像强制转换那样转换类型。
答案 5 :(得分:1)
如果DependencyObject depObj
实际上是FrameworkOtherTypeOfElement
然后depObj
不会为空
但尝试的as
广告会被评估为空,_fe
& _fce
都将为空
as
相当于做
if(I Can Cast This Object)
//Then cast it
else
//Return null