开发者

c# syntax help -> What does Get<T>() where T means

public static T Get<T>() where T : class
{
    string implName = Program.Settings[typeof(T).Name].ToString();
    object concre开发者_运维问答te = Activator.CreateInstance(Type.GetType(implName));

    return (T)concrete;
}

Please explain what does Get() where T means?

Welcome to put some reading URLs.


The where T : class puts a constrain on what types are allowed for T. This will

  1. Give you an compiler error if you put in a wrong type
  2. Give you access to access methods/properties or instantiate instances of T based on the constraint

So for your method this will produce an error if you call it like this Get<int>() since int is not a class.

public static T Get<T>() where T : class
{
    string implName = Program.Settings[typeof(T).Name].ToString();
    var implType = Type.GetType(implName);

    return (T)Activator.CreateInstance(implType);
}


This is an example of a generic. 'T' represents a type.

For example:

string result = Get<string>();

Do a Google search on Generics. This will get you started: http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx


This will constrain T to be a reference type in this particular case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜