代码之家  ›  专栏  ›  技术社区  ›  Odrade

使用运行时确定的类型实例化对象

  •  81
  • Odrade  · 技术社区  · 17 年前

    static void castTest(myEnum val)
    {
        //Call a native function that returns a pointer to a structure
        IntPtr = someNativeFunction(..params..);
    
        //determine the type of the structure based on the enum value
        Type structType = getTypeFromEnum(val);
    
        structType myStruct = (structType)Marshal.PtrToStructure(IntPtr, structType);
    }
    

    6 回复  |  直到 13 年前
        1
  •  110
  •   chakrit Dutchie432    17 年前

    有几种方法可以动态创建特定类型的对象,其中之一是:

    // determine type here
    var type = typeof(MyClass);
    
    // create an object of the type
    var obj = (MyClass)Activator.CreateInstance(type);
    

    // get type information
    var type = typeof(MyClass);
    
    // get public constructors
    var ctors = type.GetConstructors(BindingFlags.Public);
    
    // invoke the first public constructor with no parameters.
    var obj = ctors[0].Invoke(new object[] { });
    

        2
  •  13
  •   Rex M    17 年前

    dynamics

    Type type = CustomGetTypeMethod();
    var obj = Activator.CreateInstance(type);
    
    ...
    
    
    if(obj is MyCustomType)
    {
        ((MyCustomType)obj).Property1;
    }
    else if (obj is MyOtherCustomType)
    {
        ((MyOtherCustomType)obj).Property2;
    }
    
        3
  •  9
  •   Indeed is Trash    17 年前

        4
  •  5
  •   Aistina    17 年前

    创建已确定的运行时实例 Type Activator.CreateInstance Marshal.PtrToStructure 行是不可能的,因为必须在编译时知道类型才能进行强制转换。另外,请注意 不能与IntPtr结合使用。

    Object ),您可以将其转换为所述基类型并调用其上的函数。否则,只能使用反射调用函数。

    static void castTest(myEnum val)
    {
      //Call a native function that returns a pointer to a structure
      IntPtr val = someNativeFunction(..params..);
    
      //determine the type of the structure based on the enum value
      Type structType = getTypeFromEnum(val);
    
      BaseClass myStruct = (BaseClass)Marshal.PtrToStructure(IntPtr, structType);
      myStruct.SomeFunctionDeclaredInBaseClass();
    }
    

    或者:

    static void castTest(myEnum val)
    {
      //Call a native function that returns a pointer to a structure
      IntPtr val = someNativeFunction(..params..);
    
      //determine the type of the structure based on the enum value
      Type structType = getTypeFromEnum(val);
    
      object myStruct = Marshal.PtrToStructure(IntPtr, structType);
      MemberInfo[] function = FindMembers(MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance,
        (MemberFilter)delegate(MemberInfo info, object filter)
        {
          return info.Name == filter.ToString();
        }, "SomeFunction");
      if (mi.Length > 0 && mi[0] is MethodInfo)
        ((MethodInfo)mi[0]).Invoke(myStruct, ..params..);
    }
    
        5
  •  1
  •   Jakob Flygare    13 年前

    你可以去动态:

    using System;
    
    namespace TypeCaster
    {
        class Program
        {
            internal static void Main(string[] args)
            {
                Parent p = new Parent() { name = "I am the parent", type = "TypeCaster.ChildA" };
                dynamic a = Convert.ChangeType(new ChildA(p.name), Type.GetType(p.type));
                Console.WriteLine(a.Name);
    
                p.type = "TypeCaster.ChildB";
                dynamic b = Convert.ChangeType(new ChildB(p.name), Type.GetType(p.type));
                Console.WriteLine(b.Name);
            }
        }
    
        internal class Parent
        {
            internal string type { get; set; }
            internal string name { get; set; }
    
            internal Parent() { }
        }
    
        internal class ChildA : Parent
        {
            internal ChildA(string name)
            {
                base.name = name + " in A";
            }
    
            public string Name
            {
                get { return base.name; }
            }
        }
    
        internal class ChildB : Parent
        {
            internal ChildB(string name)
            {
                base.name = name + " in B";
            }
    
            public string Name
            {
                get { return base.name; }
            }
        }
    }
    
        6
  •  -5
  •   user5668312    10 年前
     methodName = NwSheet.Cells[rCnt1, cCnt1 - 2].Value2;
                                Type nameSpace=typeof(ReadExcel);
                                Type metdType = Type.GetType(nameSpace.Namespace + "." + methodName);
                                //ConstructorInfo magicConstructor = metdType.GetConstructor(Type.EmptyTypes);
                                //object magicClassObject = magicConstructor.Invoke(new object[] { });
                                object magicClassObject = Activator.CreateInstance(metdType);
                                MethodInfo mthInfo = metdType.GetMethod("fn_"+methodName);
                                StaticVariable.dtReadData.Clear();
                                for (iCnt = cCnt1 + 4; iCnt <= ShtRange.Columns.Count; iCnt++)
                                {
                                    temp = NwSheet.Cells[1, iCnt].Value2;
                                    StaticVariable.dtReadData.Add(temp.Trim(), Convert.ToString(NwSheet.Cells[rCnt1, iCnt].Value2));
                                }
    
    
                                //if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1 - 2].Value2) == "fn_AddNum" || Convert.ToString(NwSheet.Cells[rCnt1, cCnt1 - 2].Value2) == "fn_SubNum")
                                //{
                                //    //StaticVariable.intParam1 = Convert.ToInt32(NwSheet.Cells[rCnt1, cCnt1 + 4].Value2);
                                //    //StaticVariable.intParam2 = Convert.ToInt32(NwSheet.Cells[rCnt1, cCnt1 + 5].Value2);
                                //    object[] mParam1 = new object[] { Convert.ToInt32(StaticVariable.dtReadData["InParam1"]), Convert.ToInt32(StaticVariable.dtReadData["InParam2"]) };
                                //    object result = mthInfo.Invoke(this, mParam1);
                                //    StaticVariable.intOutParam1 = Convert.ToInt32(result);
                                //    NwSheet.Cells[rCnt1, cCnt1 + 2].Value2 = Convert.ToString(StaticVariable.intOutParam1) != "" ? Convert.ToString(StaticVariable.intOutParam1) : String.Empty;
                                //}
    
                                //else
                                //{
                                    object[] mParam = new object[] { };
                                    mthInfo.Invoke(magicClassObject, mParam);
    
    推荐文章