Generic method to instantiate a variable of any type (including nullable struct)?

99封情书 提交于 2019-12-13 07:36:50

问题


Let's say I have this function which instantiates a new variable with default/empty value for any type

public static T GetDefault<T>() where T : new() //body of this method is the question
{
    T t = new T();
    return t;
}

The problem with the above function is when I have something like int? for T. Because if I have

int? t = new int?();

t will be null! I do not want this to happen, instead I want the default value of int to be returned which is 0.

To solve this, I can have different overloads of GetDefault function for int?, bool? etc but that's not elegant. I can also check internally in the function if type is int? or bool? etc, but how would I go about instantiating it's base type?

Or the question boils down to how to identify if T is nullable struct and accordingly how to instantiate the nullable struct..


回答1:


Type realType = Nullable.GetUnderlyingType(typeof(T));
t = (T)Activator.CreateInstance(realType ?? typeof(T));


来源:https://stackoverflow.com/questions/12887464/generic-method-to-instantiate-a-variable-of-any-type-including-nullable-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!