如何使用字符串变量调用子类?
因此,我有一个简单的循环,我想访问类的变量
,但是有多个类,所以这就是我最终出现的循环的方式。
这就是我的代码的样子。
for (int i = 0; i<itemId.Length; i++)
{
Type type = Type.GetType(" " + itemid[i]);
object instance = Activator.CreateInstance(type);
Debug.Log(itemResponse.data.Invoke(itemid[i]).name);
}
我正在尝试访问
itemResponse.data."My String".name
要访问的课程。
公共类_1001 {}
公共类_1002 {}
公共类_1003 {}
等等,我有什么办法可以做到吗?
谢谢
So I have this simple for loop and I want to access a variable of a class
However there are multiple classes so that's how I ended up with for loop.
This is what my code looks like.
for (int i = 0; i<itemId.Length; i++)
{
Type type = Type.GetType(" " + itemid[i]);
object instance = Activator.CreateInstance(type);
Debug.Log(itemResponse.data.Invoke(itemid[i]).name);
}
I am trying to access
itemResponse.data."My String".name
The classes I want to access are.
public class _1001{ }
public class _1002{ }
public class _1003{ }
and so on, is there any way I could do that?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不建议这样做,但是如果您不想创建建议的IVSoftware这样的界面,则此功能应该执行您想要的操作。
I don't recommend doing this, but if you don't want to create an interface like IVSoftware recommended, this function should do what you want.
面向对象的编程概念
这是我能想到的最基本的演示。我已经在帖子中命名的三个类,但是还定义了一个常见的界面。
这些类中的每一个都将以特定于类的方式实现
icommon
,尤其是logdata
方法。即使我们将它们实例化为object
:该接口允许在循环
object []
基本上允许隐式铸造的情况下, 这也可以。在循环中重新提供它将具有称为
logdata
的方法。然后,它继续调用正确的班级实现,而不会大惊小怪并打扰。而且,如果您要使用不实现icommon
的对象进行尝试,则在运行时会获得invalidcastException
。循环的输出为:
The Object-Oriented Programming concept of Polymorphism can simplify solving your question. It's what's "under the hood" for the very excellent comment about implementing an interface.
Here's the most basic demo I can think of. I've made the three classes that you name in your post, but in addition have defined a common interface.
Each of these classes will implement the
ICommon
and in particular theLogData
method in its own class-specific way. This holds even if we instantiate them as typeobject
:The interface allows for implicit casting when looping the
object[]
Basically, you're promising the compiler that the object you're giving it in the loop will have a method called
LogData
. It then proceeds to call the correct class-specific implementation without a lot of fuss and bother. And if you were to attempt it with an object that doesn't implementICommon
you would get anInvalidCastException
at runtime.The output of the loop is: