是否有可能重构这个扩展方法?有可能、重构、方法

2023-09-03 08:43:03 作者:泪っ染湿衣角°

我有以下的扩展方法:

public static void ThrowIfArgumentIsNull<T>(this T value, string argument) 
    where T : class
{
    if (value == null)
    {
        throw new ArgumentNullException(argument);
    }
}

这就是它的使用的例子......

and this is an example of its usage....

// Note: I've poorly named the argument, on purpose, for this question.
public void Save(Category qwerty)
{
    qwerty.ThrowIfArgumentIsNull("qwerty");
    ....
}

工程100%的罚款。

works 100% fine.

不过,我不喜欢我怎么也得提供变量的名称,只是为了帮助我的异常信息。

But, I don't like how I have to provide the name of the variable, just to help my exception message.

我在想,如果有可能重构的扩展方法,因此它可以被称为像这样...

I was wondering if it's possible to refactor the extension method, so it could be called like this...

qwerty.ThrowIfArgumentIsNull();

和它自动计算出的变量的名称是QWERTY,因此使用该作为ArgumentNullException该值

and it automatically figures out that the name of the variable is 'qwerty' and therefore uses that as the value for the ArgumentNullException.

可能吗?我假设反射能做到这一点?

Possible? I'm assuming reflection could do this?

推荐答案

没有,你不能做到这一点。这将是很好的,但它不可能没有某种形式的AOP的介入。我敢肯定,PostSharp可以做了很好的工作,希望使用属性,并在code合同这纯粹是:

No, you can't do this. It would be nice, but it's not possible without some sort of AOP getting involved. I'm sure PostSharp can do a nice job, hopefully using attributes, and in Code Contracts it would just be:

Contract.Requires(qwerty != null);

在理想情况下,我想一个PostSharp属性,它产生code合同要求 - 我会玩的,在某些时候 - 但在那之前,你已经得到了扩展方法是最好的办法我已经发现...

Ideally I'd like a PostSharp attribute which generates the Code Contracts call - and I'll play around with that at some point - but until then, the extension method you've got is the best approach I've found...

(如果我曾经尝试PostSharp + code合同的做法,我肯定会博客一下,顺便说一句...的单丝丝可能使其比较容易了。)

(If I ever try the PostSharp + Code Contracts approach, I'll certainly blog about it, btw... Mono Cecil might make it reasonably easy too.)

编辑:为了扩大Laurent的答案,你可能有:

To expand on Laurent's answer, you could potentially have:

new { qwerty }.CheckNotNull();

如果你有很多的不可为空的参数,你可以有:

And if you had lots of non-nullable parameters, you could have:

new { qwerty, uiop, asdfg }.CheckNotNull();

这将不得不使用反射来制定出特性。有办法,你可以避免做反思每次访问,建立一个代表每个属性,一般使其whizzy。我会调查这一个博客帖子...但它有点恶心,我preFER是能够只是属性的参数的想法......

This would have to use reflection to work out the properties. There are ways that you could avoid doing the reflection on every access, building a delegate for each property and generally making it whizzy. I may investigate this for a blog post... but it's somewhat icky, and I prefer the idea of being able to just attribute the parameters...

编辑:实现code和的博客帖子正式进行。伊克,但有趣

Code implemented, and blog post duly made. Ick, but fun