简体   繁体   English

在通用方法中检查非类约束类型参数的实例是否为null

[英]Checking instance of non-class constrained type parameter for null in generic method

I currently have a generic method where I want to do some validation on the parameters before working on them. 我目前有一个通用方法,在此之前我想对参数进行一些验证。 Specifically, if the instance of the type parameter T is a reference type, I want to check to see if it's null and throw an ArgumentNullException if it's null. 具体来说,如果类型参数T的实例是引用类型,我想检查它是否为null ,如果它为null ,则抛出ArgumentNullException

Something along the lines of: 类似于以下内容:

// This can be a method on a generic class, it does not matter.
public void DoSomething<T>(T instance)
{
    if (instance == null) throw new ArgumentNullException("instance");

Note, I do not wish to constrain my type parameter using the class constraint . 注意,我不想使用class约束来约束我的类型参数。

I thought I could use Marc Gravell's answer on "How do I compare a generic type to its default value?" 我以为可以使用Marc Gravell关于“如何将泛型类型与其默认值进行比较?” 的答案 , and use the EqualityComparer<T> class like so: ,并使用EqualityComparer<T>类,如下所示:

static void DoSomething<T>(T instance)
{
    if (EqualityComparer<T>.Default.Equals(instance, null))
        throw new ArgumentNullException("instance");

But it gives a very ambiguous error on the call to Equals : 但这在调用Equals时给出了非常模糊的错误:

Member 'object.Equals(object, object)' cannot be accessed with an instance reference; 成员'object.Equals(object,object)'不能通过实例引用进行访问; qualify it with a type name instead 用类型名称代替它

How can I check an instance of T against null when T is not constrained on being a value or reference type? T不受值或引用类型的约束时,如何检查T的实例是否为null

There's a few ways to do this. 有几种方法可以做到这一点。 Often, in the framework (if you look at source code through Reflector), you'll see a cast of the instance of the type parameter to object and then checking that against null , like so: 通常,在框架中(如果您通过Reflector查看源代码),您会看到将type参数实例转换为object ,然后针对null进行检查,如下所示:

if (((object) instance) == null)
    throw new ArgumentNullException("instance");

And for the most part, this is fine. 在大多数情况下,这很好。 However, there's a problem. 但是,有一个问题。

Consider the five main cases where an unconstrained instance of T could be checked against null: 考虑以下五种主要情况,其中可以针对null检查T的无约束实例:

  • An instance of a value type that is not Nullable<T> Nullable<T>的值类型的实例
  • An instance of a value type that is Nullable<T> but is not null 一个值类型的实例Nullable<T>但不是null
  • An instance of a value type that is Nullable<T> but is null 值类型的实例 Nullable<T>但是是null
  • An instance of a reference type that is not null 引用类型的实例不为null
  • An instance of a reference type that is null 引用类型为null的实例

In most of these cases, the performance is fine, but in the cases where you are comparing against Nullable<T> , there's a severe performance hit, more than an order of magnitude in one case and at least five times as much in the other case. 在大多数情况下,性能都不错,但是在与Nullable<T>进行比较的情况下,性能受到严重影响,一种情况下超过一个数量级,而另一种情况下至少是其五倍。案件。

First, let's define the method: 首先,让我们定义方法:

static bool IsNullCast<T>(T instance)
{
    return ((object) instance == null);
}

As well as the test harness method: 以及测试工具方法:

private const int Iterations = 100000000;

static void Test(Action a)
{
    // Start the stopwatch.
    Stopwatch s = Stopwatch.StartNew();

    // Loop
    for (int i = 0; i < Iterations; ++i)
    {
        // Perform the action.
        a();
    }

    // Write the time.
    Console.WriteLine("Time: {0} ms", s.ElapsedMilliseconds);

    // Collect garbage to not interfere with other tests.
    GC.Collect();
}

Something should be said about the fact that it takes ten million iterations to point this out. 应该指出这一点,因为它需要进行一千万次迭代。

There's definitely an argument that it doesn't matter, and normally, I'd agree. 毫无疑问,这是没有关系的,通常,我会同意。 However, I found this over the course of iterating over a very large set of data in a tight loop (building decision trees for tens of thousands of items with hundreds of attributes each) and it was a definite factor. 然而,我发现这个在遍历一个非常大的数据集在紧凑循环(建筑决策树与数以百计的每个属性的数万项)的过程中,这是一个明确的因素。

That said, here are the tests against the casting method: 也就是说,以下是针对投放方法的测试:

Console.WriteLine("Value type");
Test(() => IsNullCast(1));
Console.WriteLine();

Console.WriteLine("Non-null nullable value type");
Test(() => IsNullCast((int?)1));
Console.WriteLine();

Console.WriteLine("Null nullable value type");
Test(() => IsNullCast((int?)null));
Console.WriteLine();

// The object.
var o = new object();

Console.WriteLine("Not null reference type.");
Test(() => IsNullCast(o));
Console.WriteLine();

// Set to null.
o = null;

Console.WriteLine("Not null reference type.");
Test(() => IsNullCast<object>(null));
Console.WriteLine();

This outputs: 输出:

Value type
Time: 1171 ms

Non-null nullable value type
Time: 18779 ms

Null nullable value type
Time: 9757 ms

Not null reference type.
Time: 812 ms

Null reference type.
Time: 849 ms

Note in the case of a non-null Nullable<T> as well as a null Nullable<T> ; 注意,在非null Nullable<T>以及null Nullable<T> the first is over fifteen times slower than checking against a value type that is not Nullable<T> while the second is at least eight times as slow. 第一种方法比检查非Nullable<T>的值类型要慢十五倍,而第二种方法至少要慢八倍。

The reason for this is boxing. 这样做的原因是拳击。 For every instance of Nullable<T> that is passed in, when casting to object for a comparison, the value type has to be boxed, which means an allocation on the heap, etc. 对于传入的每个Nullable<T>实例,在强制转换为object进行比较时,必须将值类型装箱,这意味着在堆上进行分配等。

This can be improved upon, however, by compiling code on the fly. 但是,可以通过动态编译代码来改进这一点。 A helper class can be defined which will provide the implementation of a call to IsNull , assigned on the fly when the type is created, like so: 可以定义一个帮助程序类,该类将提供对IsNull的调用的实现,该调用是在创建类型时即时分配的,如下所示:

static class IsNullHelper<T>
{
    private static Predicate<T> CreatePredicate()
    {
        // If the default is not null, then
        // set to false.
        if (((object) default(T)) != null) return t => false;

        // Create the expression that checks and return.
        ParameterExpression p = Expression.Parameter(typeof (T), "t");

        // Compare to null.
        BinaryExpression equals = Expression.Equal(p, 
            Expression.Constant(null, typeof(T)));

        // Create the lambda and return.
        return Expression.Lambda<Predicate<T>>(equals, p).Compile();
    }

    internal static readonly Predicate<T> IsNull = CreatePredicate();
}

A few things to note: 注意事项:

  • We're actually using the same trick of casting the instance of the result of default(T) to object in order to see if the type can have null assigned to it. 实际上,我们使用相同的技巧将default(T)结果的实例强制转换为object ,以查看类型是否可以分配null It's ok to do here, because it's only being called once per type that this is being called for. 可以在这里做,因为每个被调用的类型只被调用一次
  • If the default value for T is not null , then it's assumed null cannot be assigned to an instance of T . 如果T的默认值不为null ,则假定无法将null分配给T的实例。 In this case, there's no reason to actually generate a lambda using the Expression class , as the condition is always false. 在这种情况下,没有必要使用Expression实际生成lambda,因为条件始终为false。
  • If the type can have null assigned to it, then it's easy enough to create a lambda expression which compares against null and then compile it on-the-fly. 如果类型可以分配null ,那么创建一个与空值比较的lambda表达式就很容易了,然后即时对其进行编译。

Now, running this test: 现在,运行此测试:

Console.WriteLine("Value type");
Test(() => IsNullHelper<int>.IsNull(1));
Console.WriteLine();

Console.WriteLine("Non-null nullable value type");
Test(() => IsNullHelper<int?>.IsNull(1));
Console.WriteLine();

Console.WriteLine("Null nullable value type");
Test(() => IsNullHelper<int?>.IsNull(null));
Console.WriteLine();

// The object.
var o = new object();

Console.WriteLine("Not null reference type.");
Test(() => IsNullHelper<object>.IsNull(o));
Console.WriteLine();

Console.WriteLine("Null reference type.");
Test(() => IsNullHelper<object>.IsNull(null));
Console.WriteLine();

The output is: 输出为:

Value type
Time: 959 ms

Non-null nullable value type
Time: 1365 ms

Null nullable value type
Time: 788 ms

Not null reference type.
Time: 604 ms

Null reference type.
Time: 646 ms

These numbers are much better in the two cases above, and overall better (although negligible) in the others. 在上述两种情况下,这些数字好得多,而在其他两种情况下,总体要好(尽管可以忽略不计)。 There's no boxing, and the Nullable<T> is copied onto the stack, which is a much faster operation than creating a new object on the heap (which the prior test was doing). 没有装箱,并且Nullable<T>被复制到堆栈上,这比在堆上创建新对象(先前的测试正在做) 快得多。

One could go further and use Reflection Emit to generate an interface implementation on the fly, but I've found the results to be negligible, if not worse than using a compiled lambda. 可以走得更远,并使用Reflection Emit即时生成一个接口实现,但是我发现结果可以忽略不计,甚至比使用编译的lambda还差。 The code is also more difficult to maintain, as you have to create new builders for the type, as well as possibly an assembly and module. 该代码也更难以维护,因为您必须为该类型以及可能的程序集和模块创建新的生成器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将不受约束的泛型类型参数传递给受约束的方法 - Passing unconstrained generic type parameter to a constrained method 将约束的通用类型传递给非通用方法 - Passing Constrained Generic Type to Non-Generic Method 使用继承的泛型类型作为类型受限类的方法的输入 - Using an inherited generic type as an input to a method of a type constrained class 约束通用类型参数的继承 - Inheritance on a constrained generic type parameter 如何使用受约束的泛型类型参数将 class 实例化为派生接口 - How to instantiate a class as the interface that it derives from with constrained generic type parameter 在C#中检查泛型方法的类型参数 - Checking type parameter of a generic method in C# 使用抽象类作为方法参数和约束到所述抽象类的泛型参数之间是否有任何明显的区别? - Is there any appreciable difference between using an abstract class as a method parameter and generic parameter constrained to said abstract class? c#reflectin:为给定的类实例调用具有泛型类型和泛型参数的方法 - c# reflectin: calling method with generic type and generic parameter for given instance of class 将泛型类型的实例作为参数传递给泛型类的动态实例 - Pass an instance of a generic type as a parameter on a dynamic instance of a generic class 如何将具有约束参数类型的 class 的实例引用传递给该约束类型的实例? - How do I pass the reference of an instance from a class with a constrained parameter type, to an instance of that constraint type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM