简体   繁体   English

C#如何从另一个类的void中获取参数变量?

[英]C# How do I get an argument variable from a void in a different class?

Say I have the following: 说我有以下几点:

public class MyClass
{
    public void myVoid(int number)
    {
        //insert code here.
    }
}

Later in MyClass, the void will be called, and number will be a random value. 稍后在MyClass中,将调用void,而number将是一个随机值。

In a different class, without making a new variable in MyClass, will it be possible to receive number from myVoid? 在另一个类中,无需在MyClass中创建新变量,是否可以从myVoid接收number

I'm thinking the answer is something like: 我在想答案是这样的:

public class AnotherClass
{
    MyClass myclass = null;
    public void Start()
    {
        int theNumber = myclass.myVoid.GetFirstArgument();
    }
}

But I don't know. 但是我不知道。

If AnotherClass holds a reference on MyClass (handed in via Constructor or because it created the other instance) it can access all public fields and properties of the MyClass instance. 如果AnotherClass持有MyClass上的引用(通过构造函数或由于创建了另一个实例而提交),则它可以访问MyClass实例的所有公共字段和属性。

There are some ways to disolve the normaly strict public/private options: Protected, friends, internals. 有一些方法可以消除通常严格的公共/私人选项:受保护的,朋友的,内部的。 But you should be sure that this is what you want. 但是您应该确定这就是您想要的。

Maybe what you wanted to do was actually just create a property? 也许您想要做的实际上只是创建一个属性? myVoid looks like it might be a set function. myVoid看起来像是一个设置函数。 And it sounds like you just want to control the get functions/backing fields accessibility. 听起来您只想控制get函数/备用字段的可访问性。

You can use a property in MyClass that is set within myVoid method, assigning it the value of number. 您可以在myClass中使用myVoid方法中设置的属性,并为其分配数字值。 Then you can get the value of number in AnotherClass by accessing that property in MyClass. 然后,您可以通过访问MyClass中的该属性来获取AnotherClass中number的值。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM