是否有更多的C#“as”关键词比简单铸造? [英] Is there more to the C# "as" keyword than simple casting?

查看:142
本文介绍了是否有更多的C#“as”关键词比简单铸造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过 Josh Smith的CommandSink代码显然不明白

我不明白为什么他写的这行:

I don't understand why he wrote the line:

IsValid = _fe != null || _fce != null;

,因为他只需要写:

IsValid = depObj != null;

因为永远不会是_fe将是null和_fce not null,对?或者,我缺少关于as如何转换变量的内容?

Since it would never be the case the _fe would be null and _fce not null, or visa versa, right? Or am I missing something about how "as" casts variables?

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;
    }
    ...



ANSWER:



答案是Marc在他的评论中说这是的全部 - 它不会抛出异常 - 它只是报告null

ANSWER:

The answer is what Marc said in his comment "that is the whole point of "as" - it won't throw an exception - it just reports 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; }
    }

}


推荐答案

as 将返回您请求的类型的对象,如果操作数是兼容的。如果不是,它将返回 null 。如果您使用作为,并且可能转换失败,您需要检查以确保引用有效。

as will return an object of the type you requested, if the operand is compatible. If it isn't, it will return null. If you use as and it is possible that the cast will fail, you need to check to make sure the reference is valid.

例如,如果depObj的类型为 String ,则不会是 null ,不能转换为任何请求的类型,并且这两个变量都将变为 null

For example, if depObj was of type String, it would not be null, but it would also not be able to be converted to either of the requested types and both of those variables would become null.

这篇关于是否有更多的C#“as”关键词比简单铸造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆