简体   繁体   English

无法访问的上报字段

[英]UpCasted field without access

How can I access a field in a UpCasted Object? 如何访问UpCasted对象中的字段? I cannot use Console.WriteLine in order to print SuperPower property of a Guy object 我无法使用Console.WriteLine来打印Guy对象的SuperPower属性

namespace Test
{
    class Guy
    {
        public int Power { get; set; }
    }

    class BigGuy : Guy
    {
        public int SuperPower { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Guy guy = new Guy();
            BigGuy bigGuy = new BigGuy();
            bigGuy.SuperPower = 4;
            guy = bigGuy;
            Console.WriteLine(guy.SuperPower); // Visual studio doesn't accept this line.
        }
    }
}

When i debug I get an error: 当我调试时出现错误:

'Guy' does not contain a definition for 'SuperPower' 

Why can't I access guy.SuperPower field? 为什么我不能访问guy.SuperPower字段?

在访问BigGuy类的字段之前,您必须将guy投给BigGuy

Console.WriteLine(((BigGuy)guy).SuperPower);

Because the type of the variable is Guy . 因为变量的类型是Guy Which means you only have access to properties declared on the Guy type. 这意味着您只能访问在Guy类型上声明的属性。

Imagine if you had a second subclass: 想象一下,如果您还有第二个子类:

class FastGuy : Guy
{
    public int SpeedPower { get; set; }
}

guy = bigGuy;
guy = new FastGuy();

The properties you would be able to access would change depending on what value you're assigning. 您将能够访问的属性将根据您分配的值而变化。 That would mean it wouldn't be able to do type checking at compile time. 这意味着它将无法在编译时进行类型检查。

Typically, the point of declaring a type as some less specific type is so that you can act on the object as though it were that type, even though the concrete type may be a subclass. 通常,将类型声明为一些不太具体的类型的目的是,即使具体类型可能是子类,您也可以像对待该类型一样对对象进行操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 是否可以再次下载一个上升的对象而不为基类类型的每个派生类类型尝试强制转换? - Can an upcasted object be downcasted again without trying a cast for every derived class type of the base class type? DataContractSerializer,为什么“ this”没有被转换? - DataContractSerializer, why is “this” not upcasted? 为什么对象在上传时会保存属性 - Why an object saves properties when upcasted 在文本字段上使用 Nest Analyzer“关键字”而不访问 ElasticSearch DB - Using Nest Analyzer “keyword” on text Field without access to ElasticSearch DB 在没有时间的情况下检索日期字段的正确 SQL 查询是什么? C# 微软访问 - What's the correct SQL query to retrieve date field without time? C# MS Access 当它可以是多种类型时,如何在不将其转换为一种类型的情况下访问“对象”的特定字段? - How do I access a certain field of 'object' without casting it to one type when it can be several types? 创建方法可以访问类似的命名字段,但不具有继承的不同类型的对象 - Create method with access to similar named field, but different types of object without inheritance c# 返回向上转换的实例;原始类型 - c# return upcasted instance as it;s original type C#无法在静态上下文中访问非静态成员字段,除非实际处于静态上下文中 - C# Cannot access non-static member field in static context, without actually being in static context IMAP访问“密件抄送”字段 - IMAP Access to BCC field
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM