【问题标题】:C# creating instance of class and set properties by name in stringC#创建类的实例并在字符串中按名称设置属性
【发布时间】:2012-08-11 03:06:55
【问题描述】:

我有一些问题。我想按名称创建类的实例。 我找到了Activator.CreateInstancehttp://msdn.microsoft.com/en-us/library/d133hta4.aspx,它工作正常,我发现了这个: Setting a property by reflection with a string value 也是。

但是如何做到这一点呢?我的意思是,我知道类的名称,我知道该类中的所有属性,并且我在字符串中有这个。 例如:

string name = "MyClass";
string property = "PropertyInMyClass";

如何创建实例并为属性设置一些值?

【问题讨论】:

  • 你几乎不能这样做。从反射的角度来看,对象创建和设置属性是完全独立的事情。此外,您必须分别设置每个属性。当然,您可以创建一个辅助函数来获取您打包的字符串,将其分成几部分,分析然后创建对象并设置属性。我认为它应该为您解决问题。

标签: c# reflection


【解决方案1】:

你可以使用反射:

using System;
using System.Reflection;

public class Foo
{
    public string Bar { get; set; }
}

public class Program
{
    static void Main()
    {
        string name = "Foo";
        string property = "Bar";
        string value = "Baz";

        // Get the type contained in the name string
        Type type = Type.GetType(name, true);

        // create an instance of that type
        object instance = Activator.CreateInstance(type);

        // Get a property on the type that is stored in the 
        // property string
        PropertyInfo prop = type.GetProperty(property);

        // Set the value of the given property on the given instance
        prop.SetValue(instance, value, null);

        // at this stage instance.Bar will equal to the value
        Console.WriteLine(((Foo)instance).Bar);
    }
}

【讨论】:

  • @Darin,我测试了相同的代码,它返回错误为“无法从程序集 'GenerateClassDynamically_ConsoleApp1,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null' 加载类型 'Foo'。” .异常类型是“System.TypeLoad Exception”。我不明白它为什么会出现?
  • @Darin,我测试了相同的代码,它返回错误为“无法从程序集 'GenerateClassDynamically_ConsoleApp1,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null' 加载类型 'Foo'。” .异常类型是“System.TypeLoad Exception”。我不明白它为什么会出现?请帮我。我有获得 SAP 服务的相同要求,我需要生成类并将属性动态添加到该类并将其发送回服务以获取响应数据。
【解决方案2】:

如果你有 System.TypeLoad Exception,你的类名是错误的。

对于方法 Type.GetType,您必须输入 程序集限定名称。 那就是与项目名称例如:GenerateClassDynamically_ConsoleApp1.Foo

如果它在另一个程序集中,则必须在逗号后输入程序集名称(https://stackoverflow.com/a/3512351/1540350 上的详细信息): Type.GetType("GenerateClassDynamically_ConsoleApp1.Foo,GenerateClassDynamically_ConsoleApp1");

【讨论】:

    【解决方案3】:
    Type tp = Type.GetType(Namespace.class + "," + n.Attributes["ProductName"].Value + ",Version=" + n.Attributes["ProductVersion"].Value + ", Culture=neutral, PublicKeyToken=null");
    if (tp != null)
    {
        object o = Activator.CreateInstance(tp);
        Control x = (Control)o;
        panel1.Controls.Add(x);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-02-10
      • 2019-03-12
      • 2010-11-13
      • 2011-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 2015-11-23
      相关资源
      最近更新 更多