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
524 views
in Technique[技术] by (71.8m points)

.net - Activator.CreateInstance<T> Vs new

Is there any difference between following two ways of creating an object.

Student s1 = Activator.CreateInstance<Student>();
Student s1 = new Student();
  • Is there any difference in the way constructor is called or in initializing the memory?
  • Per my understanding, the first method looks completely redundant. If the programmer knows data type during design time, he will use the second method.
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This overload of the "Activator.CreateInstance" method is used by compilers to implement the instantiation of types specified by type parameters using generics.

Say you have the following method:

public static T Factory<T>() where T: new()
{
    return new T();
}

The compiler will convert the "return new T();" to call "CreateInstance".

In general, there is no use for the CreateInstance in application code, because the type must be known at compile time. If the type is known at compile time, normal instantiation syntax can be used (new operator in C#, New in Visual Basic, gcnew in C++).

More Info: http://msdn.microsoft.com/en-us/library/0hcyx2kd.aspx


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

1.4m articles

1.4m replys

5 comments

56.9k users

...