如何使在一种方法中创建的类的实例可用于另一种对等方法?

发布于 2024-09-25 11:41:36 字数 279 浏览 7 评论 0原文

有没有什么方法可以根据用户想要创建的数量来创建多个类对象?我能够做到这一点,但该实例仅在创建它的方法下可用

    public void Create()
    {
        //create class objects here
    }

,现在我无法在其他方法中使用它

    public void Use()
    {  
        //can't use class objects
    }

Is there any way to be able to create multiple class objects based on how many the user wants created? I was able to do this but then that instance is only available under the method that created it

    public void Create()
    {
        //create class objects here
    }

and now I wouldn't be able to use it in another method for example

    public void Use()
    {  
        //can't use class objects
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

冷心人i 2024-10-02 11:41:36

无需停下来询问您的设计决策,这里有一个直接的答案来演示使用字段的简单技术:

public class MyMainClass {
    private List<MyOtherClass> _instances = new List<MyOtherClass>();

    private void Create(int number) {
        for (int i = 0; i < number; i++) {
            this._instances.Add(new MyOtherClass());
        }
    }

    private void Use() {
        // use the first instance I created
        MyOtherClass other = this._instances[0];

        other.DoSomething();
    }
    ...
}

_instances 字段的范围为 MyMainClass。这意味着它可用于其所属类的所有实例方法(非静态)。

至于你为什么要尝试这样做,我将留给其他人。

更新:Hemant 在另一个答案中演示了一种替代技术,其中 Create 方法将实例返回给调用者。然而,我决定坚持使用字段来演示更基本的技术。

Without stopping to ask you about your design decisions, here is a straight answer to demonstrate the simple technique of using a field:

public class MyMainClass {
    private List<MyOtherClass> _instances = new List<MyOtherClass>();

    private void Create(int number) {
        for (int i = 0; i < number; i++) {
            this._instances.Add(new MyOtherClass());
        }
    }

    private void Use() {
        // use the first instance I created
        MyOtherClass other = this._instances[0];

        other.DoSomething();
    }
    ...
}

The _instances field is scoped to the MyMainClass. This means it is available to all instance methods (non-static) on the class to which it belongs.

As to why you're trying to do this, I'll leave up to someone else.

Update: an alternative techique is demonstrated by Hemant in another answer whereby the Create method returns instances to the caller. However I decided to stick with fields to demonstrate a more fundamental technique.

帅的被狗咬 2024-10-02 11:41:36

试试这个:

public MyObject[] Create()
{
    //create class objects here and return them
    return new[] {new MyObject(), new MyObject()};
}

//later
public void Use()
{  
    MyObject[] objs = Create();
    //use your objects as you like
}

Try this:

public MyObject[] Create()
{
    //create class objects here and return them
    return new[] {new MyObject(), new MyObject()};
}

//later
public void Use()
{  
    MyObject[] objs = Create();
    //use your objects as you like
}
生来就爱笑 2024-10-02 11:41:36

我认为你的意思是特定类的实例对象。请参阅此处了解类和实例的介绍

但本质上:

public class SomeClass{
   int someData;
   void SetData(int data) {
     someData = data;
   }
   int GetData() {
      return data;
   }
}

// 创建 'SomeClass' 的一些实例

var instance1 = new SomeClass();
var instance2 = new SomeClass();

实例1.SetData(2);
istance2.SetData(3);

I think you mean instance objects of a particular class. See here for an introduction to classes and instances.

but in essence:

public class SomeClass{
   int someData;
   void SetData(int data) {
     someData = data;
   }
   int GetData() {
      return data;
   }
}

// create some instances of the 'SomeClass'

var instance1 = new SomeClass();
var instance2 = new SomeClass();

instance1.SetData(2);
isntance2.SetData(3);

云胡 2024-10-02 11:41:36

在 Create() 中,您正在创建一个类,但正如您所说,无法在类之外使用它。您需要做的第一件事就是将其更改为返回对象:

public SomeType Create()
{
  //code that creates the object here.
  //Lets say it gets put into a variable called ret
  return ret;
}
public void Use()
{
  SomeType st = Create();
  //use st here.
}

或者,创建对象的方法可以将其作为参数传递给 Create,而不是使用调用 Create 的对象的方法。代码>使用(SomeType st)。

要对多个对象执行此操作,我们需要返回的不是 SomeType,而是包含多个 SomeType 对象的对象。有时我们需要关于整个集合的某些属性和方法(例如计数、在集合中前后移动的能力等等)。在这种情况下,我们将返回一个数组、一个 List、一个 HashSet 或类似 Dictionary 的内容> 视情况而定。

如果我们不需要对整个集合进行此类操作,那么返回一个 IEnumerable 会更简单、更高效,它是一个允许我们处理一系列此类对象的对象但仅此而已。 C# 具有专门用于执行此操作的语法。假设我们要返回 10 个这样的对象:

public IEnumerable<SomeType> Create()
{
  for(int i = 0; i != 10; ++i)
  {
    //code that creates the object here.
    //Lets say it gets put into a variable called ret
    yield return ret;
  }
}
public void Use()
{
  foreach(SomeType st in Create())
  {
    //use st here.
  }
}

yield 关键字很好地隐藏了关于 IEnumerable 的大量复杂性,并且让您只需编写传递每个对象的代码即可新对象(生成的代码中仍然存在复杂性,但不是您需要担心的问题)。

In Create() you are creating a class but, as you say, not able to us it outside of the class. The first thing you need to do is to change it to return the object:

public SomeType Create()
{
  //code that creates the object here.
  //Lets say it gets put into a variable called ret
  return ret;
}
public void Use()
{
  SomeType st = Create();
  //use st here.
}

Alternatively, instead of the method that uses the object calling Create, the method that creates the object could pass it as a parameter to Use(SomeType st).

To do this with multiple objects, then we need to return not a SomeType, but an object that contains those multiple SomeType objects. Sometimes we need certain properties and methods about that entire collection (e.g. the count, the ability to move back and forward through the collection and so on). In this case we would return an array, a List<SomeType>, a HashSet<SomeType> or perhaps something like Dictionary<string, SomeType> as appropriate.

If we don't need such operations on the collection as a whole then it is simpler and more efficient to return an IEnumerable<SomeType> which is an object that allows one to work through a sequence of such objects but not much else. C# has a syntax precisely for doing this. Say we're going to return 10 such objects:

public IEnumerable<SomeType> Create()
{
  for(int i = 0; i != 10; ++i)
  {
    //code that creates the object here.
    //Lets say it gets put into a variable called ret
    yield return ret;
  }
}
public void Use()
{
  foreach(SomeType st in Create())
  {
    //use st here.
  }
}

The yield keyword nicely hides a lot of complexity about IEnumerable<SomeType> and lets you just write the code that passes out each new object (that complexity is still there in the produced code, but not your problem to worry about).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文