无法访问Activator在C#中返回的对象方法

时间:2019-10-16 21:25:17

标签: c#

我想通过String动态创建对象,但是要用这段代码挣扎:

using System;
using System.Reflection;

namespace simple.test.project {

    public class Dog {
        public string Sound { get; set; } = "woof woof";
    }

    public class Animal<T> where T : new() {
        public T GetInstance() {
            return new T();
        }
    }


    class MainClass {


        public static void Main(string[] args) {

            var a = Assembly.GetExecutingAssembly().CreateInstance("simple.test.project.Dog");
            Type t_a = a.GetType();

            var a_t = typeof(Animal<>);
            var g_a_t = a_t.MakeGenericType(t_a);
            var o = Activator.CreateInstance(g_a_t);

            var dog = o.GetInstance() // object does not contain... message

        }
    }
}

最后一条语句var dog =不会被编译器接受,因为不会知道GetInstance。 代码看起来如何才能正常工作?

1 个答案:

答案 0 :(得分:-2)

让我们使用Activator.CreateInstance(Type)

public class Dog
{
    public string Sound { get; set; } = "woof woof";
}

class Program
{
    static void Main(string[] args)
    {
        var dog = (Dog)Activator.CreateInstance(typeof(Dog));

        Console.WriteLine(dog.Sound);
        dog.Sound = "Homeowner".Substring(2, 4);
        Console.WriteLine(dog.Sound);
    }
}

输出

woof woof
meow

带字符串的版本

public class Dog
{
    public string Sound { get; set; } = "woof woof";
}

public class Dog
{
    public string Sound { get; set; } = "woof woof";
}

class Program
{
    static void Main(string[] args)
    {
        var dog2 = Activator.CreateInstance(Type.GetType("Dog"));

        Console.WriteLine(dog2.GetType().GetProperty("Sound").GetValue(dog2, null));
        dog2.GetType().GetProperty("Sound").SetValue(dog2, "Homeowner".Substring(2, 4));
        Console.WriteLine(((Dog)dog2).Sound);
    }
}