在运行时将对象转换/转换为指定的类型 [英] Cast/Convert object to a specified type at runtime

查看:109
本文介绍了在运行时将对象转换/转换为指定的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在代码中的某个地方,我有一个名为class的类,可以说Class1,它看起来类似于:

Somewhere in code I have class named lets say Class1 and it look similar to:

public class Class1
{
    public int iSomeInteger;
    public double dSomeDouble;
    
    public Class1(){}
}



在另一个类中,假设Class2,我有一个带有字符串参数(要创建的类的名称)的方法.它应该像这样:



In other class, lets say Class2, I have a method with string parameter (name of the class to be created). It should like this:

DoSomethingWhenSomething(string pClassName)
{
    object o = Activator.CreateInstance(Type.GetType(pClassName));
}


并且这段代码可以正常工作.我想做的是从Class1访问公共变量(iSomeInteger,dSomeDouble)和方法,但是我看不到这些变量和方法! :(

我的无效代码是:


and this code works just fine. What I want to do is to access public variables (iSomeInteger, dSomeDouble) and mehods from Class1 but I can''t see these variables and methods! :(

My code that does not work is:

DoSomethingWhenSomething("Class1")
{
    object o = Activator.CreateInstance(Type.GetType(pClassName));
    
    // Here I want to call o.iSomeInteger but I can't! 
    o.iSomeInteger = 1; // Error raises here!
}




请帮忙:(

Pemiso




Please help :(

Pemiso

推荐答案

这可以通过两种方式完成:
1)如果两个类都具有相同的接口,则可以强制转换代码:
This can be done in two ways:
1) If both your classes have the same interface then you can cast in your code :
Isomeinterface o = (Isomeinterface)Activator.CreateInstance(Type.GetType(pClassName));
    
    // Here I want to call o.iSomeInteger but I can't! 
    o.iSomeInteger = 1; // assuming the interface has this method


2)使用反射


2) Use reflection

PropertyInfo prop = o.GetType().GetProperty("iSomeInteger ", BindingFlags.Public | BindingFlags.Instance);
if(null != prop && prop.CanWrite)
{
    prop.SetValue(o, 1, null);
}


您不能将其引用为对象,然后在编译时使用派生类中的属性-就像编写
You can''t refer to it as an object and then use the properties in a derived class at compile time - that woudl be like writing
string s = "hello|goodbye";
DropDownList d = new DropDownList();
object o = s;
if (myBool) o = d;
string[] p = o.Split('|');

尽管在某些情况下o可能包含字符串,但在某些情况下可能不包含字符串.由于只有字符串实例具有Split方法,因此您无法编译可能引用不存在的方法的代码!

您只能引用在当前类或从其派生的类中定义的类的属性和方法.您不能将类或引用的变量的类型派生到类中的属性或方法.

您将必须使用反射以类似于创建对象的方式来访问对象的属性.

Although in some cases o may contain a string, there are cases when it doesn''t. Since only the string instances have a Split method, you can''t compile code that could refer to a method that doesn''t exist!

You can only refer to properties and methods of classes defined in the current class or in classes it is derived from. You cannot rafer to properties or method in classes which are derived from the type of the variable you are referencing.

You will have to use reflection to access the properties of your object in a similar manner to the way you created it.


这篇关于在运行时将对象转换/转换为指定的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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