如何在C#中使用方法(如果可能)实例化类?
假设您有某种控制台应用程序游戏,并且在游戏中您创建了一个具有自己的类的对象。当游戏仍在运行时,您如何使用方法或函数之类的东西创建该类的实例。
我查遍了互联网,几周后还没有找到任何东西。通常,我只会为该类创建一个数组,并向其中添加新实例,如下所示。
class MyClass
{
//fields and methods
}
class Program
{
static void Main(string[] args)
{
MyClass[] myClasses = new MyClass[16];
myClasses.SetValue(new MyClass(), 0);
}
}
但这感觉笨拙且低效。我希望我能尽快弄清楚这一点。
Say you had some sort of console-application game, and inside the game you create an object which would have it's own class. How would you make an instance of that class with something like a method or function while the game might still be running.
I've looked all over the internet and haven't found anything after weeks. Normally, I would just create an array for the class and add new instances to it like so.
class MyClass
{
//fields and methods
}
class Program
{
static void Main(string[] args)
{
MyClass[] myClasses = new MyClass[16];
myClasses.SetValue(new MyClass(), 0);
}
}
But this feels clunky and inefficient. I hope I figure this out soon.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有很多方法可以做到这一点。最常见和接受的方式可能是
FactoryPattern
。创建您的工厂:
然后只需在代码中调用它:
There are many ways to do this. The most common and accepted way may be the
FactoryPattern
.Create your factory:
Then simply call it in your code:
你是否正在尝试这样做:
Are you trying to do this: