我正在通過Josh Smith's CommandSink code工作,顯然不明白C#中的「as」關鍵字。有沒有更多的C#「as」關鍵字比簡單鑄造?
我不明白爲什麼他寫的一行:
IsValid = _fe != null || _fce != null;
,因爲他只需要這樣寫:
IsValid = depObj != null;
由於它永遠不會是這樣的_fe將是無效和_fce不爲空,或反之亦然,對嗎?或者我錯過了「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;
}
...
答:
答案是什麼馬克在他的評論「是整點‘說,’ - 它不會拋出一個異常 - 它只是報告空。 「
,這裏是證明:
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; }
}
}
啊,你每天都會學到新的東西。我會建議類似的東西,但假設它會拋出一個異常,如果它不能投... – 2009-04-21 08:40:07
@戈登 - 這是「as」的整個點 - 它*不會拋出異常 - 它只是報告爲空。 – 2009-04-21 08:41:39