本文介绍了Activator.CreateInstance()和typeof运算(T).InvokeMember()与BindingFlags.CreateInstance之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请原谅我,如果这个问题已经被问和回答。

Forgive me if this question has already been asked and answered.

由于一类T型的,什么是下?

Given a class of type T, what is the difference between the following?

T myObj = Activator.CreateInstance<T>();

T myObj = typeof(T).InvokeMember(null, BindingFlags.CreateInstance, null, null, null);

时pferred在另一个解决方案$ P $?

Is one solution preferred over the other?

推荐答案

反编译 RuntimeType.InvokeMember 产生这个片断:

if ((bindingFlags & BindingFlags.CreateInstance) != BindingFlags.Default)
{
    if (((bindingFlags & BindingFlags.CreateInstance) != BindingFlags.Default) && ((bindingFlags & (BindingFlags.SetProperty | BindingFlags.GetProperty | BindingFlags.SetField | BindingFlags.GetField | BindingFlags.InvokeMethod)) != BindingFlags.Default))
    {
        throw new ArgumentException(Environment.GetResourceString("Arg_CreatInstAccess"), "bindingFlags");
    }
    return Activator.CreateInstance(this, bindingFlags, binder, providedArgs, culture);
}

在换句话说, InvokeMember 的BindingFlags 要求 Activator.CreateInstance 。它越来越正事之前,经过几个调用层(检查绑定,验证参数)。 Activator.CreateInstance&LT; T&GT; 更加简洁:

In other words, InvokeMember with those BindingFlags calls Activator.CreateInstance. It goes through several more call layers (checking bindings, verifying arguments) before getting down to business. Activator.CreateInstance<T> is much more succinct:

public static T CreateInstance<T>()
{
    bool bNeedSecurityCheck = true;
    bool canBeCached = false;
    RuntimeMethodHandle emptyHandle = RuntimeMethodHandle.EmptyHandle;
    return (T) RuntimeTypeHandle.CreateInstance(typeof(T) as RuntimeType, true, true, ref canBeCached, ref emptyHandle, ref bNeedSecurityCheck);
}

EDITED 您可能希望后者要快,但调用方法 RuntimeType.CreateInstanceSlow 还要求的RuntimeTypeHandle。的CreateInstance 做的工作;使用它作为后备,如果无法找到为构造一个激活缓存条目。我会做一些性能测试,如果你正在寻找两人的最快的解决方案。

EDITED You might expect the latter to be faster, but a method called RuntimeType.CreateInstanceSlow also calls RuntimeTypeHandle.CreateInstance to do the work; it's used as a fallback if an Activator cache entry for the constructor can't be found. I'd do some performance testing if you're looking for the fastest solution of the two.

这篇关于Activator.CreateInstance()和typeof运算(T).InvokeMember()与BindingFlags.CreateInstance之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-09 23:13