English 中文(简体)
创建一种类型,作为方法的参数
原标题:Create an instance of a Type, provided as a parameter to a method

即时:

public class InstantiateMe
{
    public String foo
    {
        get;
        set;
    }
}

缩略语:

public void CreateInstanceOf(Type t)
{
    var instance = new t();

    instance.foo = "bar";
}

鉴于我所希望取得成就的活力,我对我需要利用思考来做到这一点感到困惑。

我的成功标准如下:

  • Create an instance of any type
  • Create instances of types without having to invoke their constructor
  • Access all public properties

我非常赞赏一些行之有效的榜样。 我不喜欢C#,但我以前从未思考过。

最佳回答

你基本上需要利用反思。 利用Activator.CreateInstance()来构造你的类型,然后打电话Invoke Members()

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
    );
}

查阅一般类型的所有特性,并设计/设计这些特性,可使用GetProperties()

foreach (PropertyInfo property in type.GetProperties())
{ 
    property.GetValue() // get property
    property.SetValue() // set property
}   

另见文件,供更多使用InvokeMember()。

问题回答

恳请以下人士实际成立。

Object t = Activator.CreateInstance(t);

然而,如你的例子所示,如果没有一般性规定和制约因素,就不可能静态地接触各位成员。

您可以采取以下行动:

public void CreateInstanceOf<T>() where T : InstantiateMe, new()
{
    T i = new T();
    i.foo = "bar";
}

既然你有希望进行即时的类型,你可以采用一种通用的帮助方法:

public static T New() where T : new()
{
    return new T();
}

如果你在撤出某些地方(如有活力的装货组),而且你不能直接接触这些类型(即某种美分方案或反映数据),那么你就应当使用反思。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签