如何更改C#中的默认值(T)?

Jan*_*son 14 c# linq default nullable

我想改变默认(T)对某些类的行为.因此,我想返回一个null对象,而不是为我的引用类型返回null.

有一些像

kids.Clear();
var kid = kids.Where(k => k.Age < 10).SingleOrDefault(); 

if (kid is NullKid)
{
  Console.Out.WriteLine("Jippeie");
}
Run Code Online (Sandbox Code Playgroud)

任何人都知道这是否可能?

slo*_*oth 13

任何人都知道这是否可能?

根本不可能.

但也许您想要使用DefaultIfEmpty:

kids.Clear(); 
var kid = kids.Where(k => k.Age < 10).DefaultIfEmpty(NullKid).Single(); 

if (kid == NullKid)
{  
    Console.Out.WriteLine("Jippeie");
}
Run Code Online (Sandbox Code Playgroud)


Wil*_*ean 9

您不能更改默认值(T) - 它对于引用类型始终为null,对于值类型为零.


Che*_*hen 2

我想你已经在你的问题中得到了答案:if/switch 语句。像这样的东西:

if (T is Dog) return new Dog(); 
   //instead of return default(T) which is null when Dog is a class
Run Code Online (Sandbox Code Playgroud)

您可以像这样创建自己的扩展方法:

public static T SingleOrSpecified<T>(this IEnumerable<T> source, Func<T,bool> predicate, T specified)
{
    //check parameters
    var result = source.Where(predicate);
    if (result.Count() == 0) return specified;
    return result.Single();   //will throw exception if more than 1 item
}
Run Code Online (Sandbox Code Playgroud)

用法:

var p = allProducts.SingleOrSpeficied(p => p.Name = "foo", new Product());
Run Code Online (Sandbox Code Playgroud)