【发布时间】:2018-01-02 20:51:19
【问题描述】:
我制作了 Animal 项目并将其设置为 Library。当然在 Animal 项目中我会添加更多的类。在这个项目中,我现在有 2 个类:Dog 和 Method。
//Class Method
public class Method : Attribute{
public string Name { get; set; }
public Method(){
Name = "";
}
}
//Class Dog
[Method(Name = "dog")]
public class Dog
{
public int NumberOfLegs { get; set; }
public string Breed { get; set; }
public Dog() { }
}
然后我在我的解决方案 Ref 中创建了第二个项目,它是我的主类:
//version 1
class Program{
public static Dictionary<String, Type> animals;
static void Main(string[] args){
Assembly assembly = Assembly.GetEntryAssembly();
Type[] typ = assembly.GetTypes();
foreach (Type t in typ){
animals.Add(t.Name, t);
}
}
}
我想实现“狗,狗”,“猫,猫”,“老鼠,老鼠”。其中“dog”是名称属性,而“Dog”是一种类型,因为我可以制作类似
的东西Activator.CreateInstance(animals[nameAnimal]);
但是现在我做错了,我的方法行不通,我在 .net 核心中找不到解决问题的方法。我只想要属性方法所在的类中的对象。如何实现?
编辑。 我的程序没有看到库“Dog”并搜索“Ref.*”库,例如 Ref、Ref.Program 等。
【问题讨论】:
-
什么不起作用?
-
你在使用 Visual Studio 吗?
-
@JonathanWillcock 是的,2017 年
-
你知道如何提取类型属性吗?请看这个stackoverflow.com/questions/2656189/…
标签: c# reflection .net-core