实例化任何类型(包括可为空结构)的变量的通用方法? [英] Generic method to instantiate a variable of any type (including nullable struct)?

查看:74
本文介绍了实例化任何类型(包括可为空结构)的变量的通用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个函数,它实例化一个 new 变量,具有默认/空值,适用于任何类型

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

上述函数的问题是当我有类似 int?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 将为空!我不希望这种情况发生,而是希望返回 int 的默认值,即 0.

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.

为了解决这个问题,我可以为 int?bool? 等使用不同的 GetDefault 函数重载,但这并不优雅.如果类型是 int?bool? 等,我也可以在函数内部检查,但是我将如何实例化它的基本类型?

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?

或者问题归结为如何识别 T 是否为可空结构,以及如何实例化可空结构..

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

推荐答案

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

这篇关于实例化任何类型(包括可为空结构)的变量的通用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆