[英]Instantiating Object in a method from Type passed as parameter
I'm trying to pass a Type to a method and have it instantiate an Object of said Type. 我试图将类型传递给方法,并使其实例化所述类型的对象。 I have a lot of repeated code which resembles: 我有很多重复的代码,类似于:
foreach (Link link in links)
{
Object obj = new Object(link);
list.Add("Description" + obj.prop.ToString());
}
With numerous different classes/objects. 具有许多不同的类/对象。
I envision: 我设想:
private void populateList(List<Link> links, Type type, List<val> list, string desc)
{
foreach (Link link in links)
{
//Instantiate Object from type parameter here?
list.Add(desc + obj.prop.ToString());
}
}
I attempted to use Generics and Reflection to solve the problem: 我试图使用泛型和反射来解决问题:
Type[] typeArgs = {typeof(Link)};
Type constructed = type.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(constructed);
But I wasn't too sure where to go next as I'm not able to use either o or constructed to do what I need. 但是我不太确定下一步该怎么做,因为我无法使用o或构造函数来执行所需的操作。
I'm a complete beginner with Reflection and Generics so I'm not even sure if what I'm asking is possible. 我是反射和泛型的完全入门者,所以我甚至不确定我要问的内容是否可行。 I'd appreciate any advice on where to go next or any potential solutions. 我将对下一步的建议或任何可能的解决方案表示感谢。
Reflection works for this purpose 反射为此目的而工作
public static T GenerateNewInstance<T>(T obj) where T : class
{
Type type = typeof (T);
object instance = Activator.CreateInstance(type);
return instance as T;
}
I think what you're having trouble with is accessing the object properties (prop?) The compiler doesn't know what specific object type you're working with as it's being cast as an object. 我认为您遇到的麻烦是访问对象属性(prop?)。编译器在将其转换为对象时,不知道您使用的是哪种特定对象类型。
You could make that work runtime using something like: 您可以使用以下方法使该工作运行时:
obj.GetType().GetRuntimeProperty("PropertyName").GetValue(obj);
But ultimately it's a matter of casting the object to a specific class: 但最终这只是将对象强制转换为特定类的问题:
class obj = (class)obj;
list.Add(obj.property.ToString());
Edit: I might not understand your question correctly. 编辑:我可能无法正确理解您的问题。 It also seems like you want to pass different type's. 似乎您也想传递不同的类型。 Does the original classes have identical properties or do you just want to add all the properties from a given object into the list? 原始类是否具有相同的属性,还是只想将给定对象的所有属性添加到列表中?
If they have identical properties, consider creating an interface with those properties and make your classes implement it, that way you can create a new instance of the objects and cast it as the interface and thereby get the properties they share. 如果它们具有相同的属性,请考虑使用这些属性创建一个接口并让您的类实现该接口,这样您就可以创建对象的新实例并将其强制转换为接口,从而获得它们共享的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.