default(t)在泛型中用于安全获取类型t的默认值,无论t是引用类型还是值类型。1. 当t为引用类型时,default(t)返回null;2. 当t为值类型时,返回其零初始化值(如int为0,bool为false);3. 它解决了泛型代码中因类型不确定性导致的初始化难题,避免了使用null或0带来的编译错误;4. 相比new t()(需无参构造函数约束)和null(仅适用于引用类型),default(t)更通用且类型安全;5. 在初始化泛型字段、返回“未找到”结果、设置out参数默认值等场景下,应优先使用default(t)以确保代码的简洁性与鲁棒性。

C#中
default
在我看来,
default
class
null
int
struct
null
0
这时候,
default(T)
T
default(T)
null
T
default(T)
int
0
bool
false
DateTime
MinDate
T
这种设计,让泛型代码在面对各种类型时都能保持其鲁棒性和一致性,避免了繁琐的类型检查和条件分支。
public class GenericProcessor<T>
{
    private T _data;
    public GenericProcessor()
    {
        // 无论T是什么类型,都能安全地初始化为默认值
        _data = default(T); 
        Console.WriteLine($"Initialized with default value: {_data ?? (object)"(null)"}");
    }
    public T GetDefaultValue()
    {
        return default(T);
    }
    public bool IsDefault(T value)
    {
        // 比较一个值是否是其类型的默认值
        return EqualityComparer<T>.Default.Equals(value, default(T));
    }
    // 假设我们有一个方法,可能返回T,也可能因为某种原因返回其默认值
    public T FindItemOrDefault(bool found)
    {
        if (found)
        {
            // 假设这里找到一个具体的值
            if (typeof(T) == typeof(string))
            {
                return (T)(object)"Found String";
            }
            else if (typeof(T) == typeof(int))
            {
                return (T)(object)123;
            }
            // 更多类型处理...
            return default(T); // 或者返回一个实际值
        }
        else
        {
            // 没有找到,返回默认值
            return default(T); 
        }
    }
}
// 示例用法:
// var intProcessor = new GenericProcessor<int>(); // 输出:Initialized with default value: 0
// var stringProcessor = new GenericProcessor<string>(); // 输出:Initialized with default value: (null)
// var customClassProcessor = new GenericProcessor<MyClass>(); // 输出:Initialized with default value: (null)
// Console.WriteLine(new GenericProcessor<int>().GetDefaultValue()); // 输出:0
// Console.WriteLine(new GenericProcessor<string>().GetDefaultValue() ?? "(null)"); // 输出:(null)
// Console.WriteLine(new GenericProcessor<DateTime>().GetDefaultValue()); // 输出:1/1/0001 12:00:00 AM
// Console.WriteLine(new GenericProcessor<int>().IsDefault(0)); // True
// Console.WriteLine(new GenericProcessor<string>().IsDefault(null)); // True
// Console.WriteLine(new GenericProcessor<string>().IsDefault("hello")); // False在我早期的编程生涯中,写泛型代码时,如果需要初始化一个未知类型的变量,那简直是噩梦。最常见的痛点就是:我到底应该给它赋
null
0
设想一下,你有一个泛型方法,像这样:
public T GetSomeValue<T>()
{
    // 我需要在这里初始化一个T类型的变量
    T result; 
    // 如果T是引用类型,我可以写 result = null;
    // 如果T是int,我可以写 result = 0;
    // 但我怎么知道T是什么呢?
    // result = null; // 如果T是int,编译错误!
    // result = 0;    // 如果T是string,编译错误!
    // 甚至 try-catch 都不行,因为这是编译时的问题。
    // 没 default(T) 的时候,你可能被迫这样写:
    // if (typeof(T).IsClass) { result = null; }
    // else if (typeof(T).IsValueType) { result = Activator.CreateInstance<T>(); } // 这又引出新问题:值类型可能有构造函数,但默认构造函数呢?
    // 这种代码不仅啰嗦,还充满了反射,性能和可读性都很差。
    return result; // 编译错误:未赋值的局部变量
}default(T)
T
理解
default(T)
new T()
null
default(T)
T
null
int
0
bool
false
struct
T
default
new T()
T
T
where T : new()
T
int
string
new int()
int
0
public class MyClass<T> where T : new() { T instance = new T(); }null
Nullable<T>
int?
int i = null;
T
T variable = null;
总结一下,
default(T)
new T()
null
default(T)
在我自己的开发实践中,我发现
default(T)
初始化泛型集合或数据结构中的元素: 当你构建一个泛型链表、栈、队列或者自定义的字典时,如果需要在内部数组或节点中预分配空间,或者需要一个“空”占位符时,
default(T)
public class MyGenericArray<T>
{
    private T[] _elements;
    public MyGenericArray(int capacity)
    {
        _elements = new T[capacity];
        // 数组创建后,引用类型元素默认为null,值类型元素默认为0。
        // 但如果我想明确地将某个位置设置为“空”或“未初始化”状态,
        // 即使是值类型,default(T)也能清晰表达意图。
        // 例如,在某些自定义的哈希表中,可能需要用default(T)来标记空槽位。
    }
}泛型方法的返回值,表示“未找到”或“失败”: 当你的泛型方法尝试查找某个元素,或者执行某个操作但可能失败时,返回
default(T)
null
T
public T FindFirst<T>(IEnumerable<T> collection, Func<T, bool> predicate)
{
    foreach (var item in collection)
    {
        if (predicate(item))
        {
            return item;
        }
    }
    // 如果遍历完都没找到,就返回该类型的默认值
    return default(T); 
}作为泛型参数的out
ref
out
ref
default(T)
public bool TryParseGeneric<T>(string input, out T result)
{
    // 假设这里有一些解析逻辑
    if (typeof(T) == typeof(int) && int.TryParse(input, out int intVal))
    {
        result = (T)(object)intVal;
        return true;
    }
    else if (typeof(T) == typeof(string))
    {
        result = (T)(object)input;
        return true;
    }
    // 如果解析失败,或者不支持该类型,就返回默认值
    result = default(T); 
    return false;
}在泛型类中声明字段或属性时,为其提供默认初始值: 如果你有一个泛型类,其中包含一个
T
default(T)
public class CacheEntry<T>
{
    public string Key { get; set; }
    public T Value { get; set; }
    public DateTime Expiry { get; set; }
    public CacheEntry(string key)
    {
        Key = key;
        Value = default(T); // 初始时,值可以为默认值
        Expiry = DateTime.MaxValue; // 或者其他默认过期时间
    }
}总而言之,只要你需要在泛型上下文中获取一个“空”、”零化”或“未初始化”的值,并且不确定具体类型是引用类型还是值类型,
default(T)
以上就是C#的default关键字在泛型中的作用是什么?的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号