这个关键字(as)运算符有什么问题? [英] what is problem in this key word (as) operator?

查看:91
本文介绍了这个关键字(as)运算符有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class class1
{ }
class class2
{ }
class Program
{
    static void Main(string[] args)
    {

        class2 ob2 = new class2();
        class1 ob1= ob2 as class1; //ERROR IS
                                   // convert type class2 to class1
                                   // via reference conversion ,boxing conversion,
                                   // unboxing conversion ,wrapping conversion ,
                                   //or null type conversion .



    }
}

推荐答案

它(编译器)静态已知运算符失败(将返回 null ,因为 class1 不是 class2 )如果是的话。比较:



It statically already known (to the compiler) that the operator fails (would return null because class1 is not class2) if it is. Compare:

class Base {}
class Derived : Base {}

//...

Base base = new Derived();
//Derived derived = base; // will not compile
Derived derived = base as Derived; // will compile, return reference to base as Derived, because this is its run-time type

object ob2 = new class2();
class1 ob1= ob2 as class1; // will compile because object (as compile-time) can be a code1 (as run-time) type, and returns null because actually it's not the case





您显然需要获得运行时的概念编译类型类型以及与继承相关的赋值兼容性。背景很简单。

如果你通过变量/ less派生类型的成员使用更多派生类的对象,你总是纠正:你只使用派生类型较少的成员,由于继承,它总是出现在派生类型中。相反的情况将是危险的:它将使代码访问实际上不存在于运行时类型中的成员。在.NET中,这是受保护的:没有直接赋值兼容性(不会在没有向下转换的情况下编译),使用(MyType)下载myObject 语法将抛出异常,使用向下转换为将返回 null



-SA



You apparently need to get the concept of run-time and compile-type types and assignment-compatibility related to inheritance. The background is simple enough.
If you use more the object of most derived class through the variable/member of less derived type, you always correct: you operate only with the members of the less derived type, which always present in the derived type due to inheritance. The opposite situation would be dangerous: it would give the code access to members which do not actually exist in run-time type. In .NET, this is protected: there is no direct assignment compatibility (will not compile without down-casting), down-casting with (MyType)myObject syntax will throw exception, down-casting with as will return null.

—SA


Obj2是一个class2,它不是1级,编译器也不知道如何制作它。





这就像说:



Obj2 IS a class2, it isn''t a class 1 and the compiler doesn''t know how to make it one.


It''s like saying:

volcano vesuvius = new volcano();

dog rover = vesuvius AS dog;





所有编译器都说:



什么



All the compiler is saying is:

"What the


!@#


这篇关于这个关键字(as)运算符有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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