ObjectType instance =(ObjectType)System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(typeName: objectType.FulName, // string including namespace of the typeignoreCase: false,bindingAttr: BindingFlags.Default,binder: null, // use default binderargs: new object[] { args, to, constructor },culture: null, // use CultureInfo from current threadactivationAttributes: null);
使用TypeDescriptor的示例:
ObjectType instance =(ObjectType)System.ComponentModel.TypeDescriptor.CreateInstance(provider: null, // use standard type description provider, which uses reflectionobjectType: objectType,argTypes: new Type[] { types, of, args },args: new object[] { args, to, constructor });
Public Function CloneObject(Of T As New)(ByVal src As T) As TDim result As T = NothingDim cloneable = TryCast(src, ICloneable)If cloneable IsNot Nothing Thenresult = cloneable.Clone()Elseresult = New TCopySimpleProperties(src, result, Nothing, "clone")End IfReturn resultEnd Function
对于非泛型,假设该类型具有默认构造函数和捕获如果没有,则会出现异常。
Public Function CloneObject(ByVal src As Object) As ObjectDim result As Object = NothingDim cloneable As ICloneableTrycloneable = TryCast(src, ICloneable)If cloneable IsNot Nothing Thenresult = cloneable.Clone()Elseresult = Activator.CreateInstance(src.GetType())CopySimpleProperties(src, result, Nothing, "clone")End IfCatch ex As ExceptionTrace.WriteLine("!!! CloneObject(): " & ex.Message)End TryReturn resultEnd Function