有可能引用一个像这样被初始化的类......? [英] Is it possible to reference a class that's been initialized like this...?

查看:53
本文介绍了有可能引用一个像这样被初始化的类......?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我初始化这样的类:



If I initialize a class like this:

Human tom = new Human(new GorillaHead(), new HumanTorso(), new HumanLegs());





我再也无法访问GorillaHead()了吧?我必须先将它作为Human类签名之外的命名实例吗?



我尝试过:



这是有效的:





I can't access GorillaHead() again, right? I'd have to make it a named instance outside of the Human class signature first right?

What I have tried:

This works:

var gorillahead = new GorillaHead();
var humantorso = new HumanTorso();
var humanlegs = new HumanLegs();
Human tom = new Human(gorillahead, humantorso, humanlegs);

推荐答案

不,你将无法在 Human 类之外访问它们。



大概是你的人类 class应具有访问方法或属性:

No, you won't be able to access them outside of the Human class.

Presumably your Human class should have access methods or properties :
var head = tom.Head; // you will get the GorillaHead 
var torso = tom.Torso; // you will get the HumanTorso
var legs = tom.Legs; // you will get the HumanLegs


除了这里提到的那些之外,还有很多方法可以创建/控制/限制Tom的...... errr ... mmmm ...身体部位的曝光。



1.具有返回值的公共函数或值:
There are so many ways you can create/control/limit the exposure of Tom's ... errr ... mmmm ... body parts in addition to those mentioned here.

1. have public functions that return the value, or values:
public GorillaHead GetGHead(Human human, Userstatus ustatus)
{
     if(human != null && (ValidateStatus(human, ustatus) > Userstatus.Serf) && human.GorillaHead != null)
    {
         return human.GorillaHead;
    }
    return null;
}

2。使用C#7新的Tuple语义来返回一堆不同类型的值:

2. use C# 7 new Tuple semantics to return a bunch of different types of values:

public (GorillaHead head,Torso torso, Legs legs) GetParts(Human human)
{
   return (human.GorillaHead, human.Torso, human.Legs);
}


这取决于您的班级的样子,使用公共属性或公共变量,例如 Gorilla ,然后您可以引用这些属性。请参阅此处的示例: [ Dotnetperls ]

示例:

It depends on how your class looks like, if you use public properties, or public variables e.g. Gorilla, then you can reference the properties. See example here: [Dotnetperls]
Example:
public class Human
{
    public string Gorilla { get; set; }
    public string Torso { get; set; }
    public string Legs { get; set; }

    // Constructor
    public Human(string gorilla, string torso, string legs)
    {
       Gorilla = gorilla;
       Torso = torso;
       Legs = legs;
    }
}

另见:使用构造函数(C#编程指南)| Microsoft Docs [ ^ ]


这篇关于有可能引用一个像这样被初始化的类......?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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