创建一个Type的实例,作为方法的参数提供 [英] Create an instance of a Type, provided as a parameter to a method
问题描述
实例化的类:
pre $ public class InstantiateMe
{
public String foo
{
get;
set;
一些伪代码:
public void CreateInstanceOf(Type t)
{
var instance = new t();
instance.foo =bar;
$ / code>
到目前为止,我认为我需要使用反射来完成这项工作,这是我想达到的动态性质。
这是我的成功标准:
我非常感谢一些有效的示例代码。我不是新来的C#,但我从来没有使用过反射之前。
你基本上需要使用反射。使用> Activator.CreateInstance()
来构造您的类型,然后在该类型上调用 InvokeMember()
来设置属性:
public void CreateInstanceOfType(Type t)
{
var instance = Activator.CreateInstance(t) ; //创建实例
//设置实例的属性
t.InvokeMember(
foo,//属性名称
BindingFlags.SetProperty,
null,
obj,
new Object [] {bar} //属性值
);
$ / code>
要访问泛型类型的所有属性并设置/获取它们,可以使用 GetProperties()
,它返回一个 PropertyInfo
集合,您可以遍历它:
foreach(type.GetProperties()中的PropertyInfo属性)
{
property.GetValue()//获取属性
property.SetValue()//设置属性
}
另请参阅文档了解更多使用 InvokeMember() code>。
The class to instantiate:
public class InstantiateMe
{
public String foo
{
get;
set;
}
}
Some pseudo-code:
public void CreateInstanceOf(Type t)
{
var instance = new t();
instance.foo = "bar";
}
So far I'm figuring that I need to use reflection to get this done, given the dynamic nature of what I want to achieve.
Here's my success criteria's:
- Create an instance of any type
- Create instances of types without having to invoke their constructor
- Access all public properties
I would greatly appreciate some working example-code. I'm not new to C#, but I've never worked with reflection before.
You'd basically need to use Reflection. Use Activator.CreateInstance()
to construct your type and then call InvokeMember()
on the type, to set the property:
public void CreateInstanceOfType(Type t)
{
var instance = Activator.CreateInstance(t); // create instance
// set property on the instance
t.InvokeMember(
"foo", // property name
BindingFlags.SetProperty,
null,
obj,
new Object[] { "bar" } // property value
);
}
To access all the properties of the generic type and set/get them, you can use GetProperties()
which returns a PropertyInfo
collection, which you can iterate through:
foreach (PropertyInfo property in type.GetProperties())
{
property.GetValue() // get property
property.SetValue() // set property
}
Also, see the documentation for more ways of using InvokeMember()
.
这篇关于创建一个Type的实例,作为方法的参数提供的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!