Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

c# - Difference between Activator.CreateInstance() and typeof(T).InvokeMember() with BindingFlags.CreateInstance

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

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

Is one solution preferred over the other?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Decompiling RuntimeType.InvokeMember yields this fragment:

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

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...