用两个通用类型参数推断通用类型

用两个通用类型参数推断通用类型

本文介绍了用两个通用类型参数推断通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法

public bool HasTypeAttribute<TAttribute, TType>(TType obj)
{
    return typeof(TType).GetCustomAttribute<TAttribute>() != null;
}

并且我希望能够像这样使用它:

and I want to be able to use it like this:

MyClass instance = new MyClass();

TypeHelper.HasTypeAttribute<SerializableAttribute>(instance);

但是由于

所以我需要打电话

TypeHelper.HasTypeAttribute<SerializableAttribute, MyClass>(instance);

这当然是有道理的,但是为什么编译器不能推断出所传递对象的类型?因为如果该方法看起来像这样:

which certainly makes sense, but why can the compiler not infer the type of the passed object? Because if the method looked like this:

public void Demo<T>(T obj)
{
}

编译器当然可以推断类型,以便我可以编写

the compiler would certainly be able to infer the type, so that I can write

Foo.Demo(new Bar());

代替

Foo.Demo<Bar>(new Bar());

那么,在这种情况下,有没有办法使类型推断起作用?这是我的设计缺陷,还是可以实现我想要的?重新排序参数也无济于事...

So, is there a way to make type inference work in this case? Is it a design flaw by me or can I achieve what I want? Reordering the parameters doesn't help too...

推荐答案

因为C#规则不允许这样做.

Because the C# rules don't allow that.

C#制定一条规则是可行的:如果某些类型与参数相关(因此至少可以在某些时候被推断出),并且显式给定类型的数量与剩余数量相同不可推论的类型,那么两者将协同工作.

It would be feasible for C# to have a rule where if some of the types related to parameters (and hence could be inferred at least some of the time) and the number of explicitly given types was the same as the number of remaining un-inferrable types, then the two would work in tandem.

这需要有人提出来,说服参与C#决策的其他人,这是一个好主意,然后才能实施.这还没有发生.

This would need someone to propose it, convince other people involved in the decision-making around C# it was a good idea, and then for it to be implemented. This has not happened.

除了功能开始必须证明自己值得为其带来的额外复杂性(将任何内容添加到语言中,并且随着工作量的增加,编译器错误的可能性增加等等,它会立即变得更加复杂)的事实之外,问题是,这是个好主意吗?

Aside from the fact that features start off having to prove themselves worth the extra complexity they bring (add anything to a language and it is immediately more complex with more work, more chance of compiler bugs etc.) the question then is, is it a good idea?

另外,在此特定示例中,您的代码会更好.

On the plus, your code in this particular example would be better.

不利的是,每个人的代码现在都稍微复杂一些,因为错误的东西有更多的方式可以出错,从而导致代码在运行时失败而不是在编译时失败,或者导致错误信息更少.

On the negative, everyone's code is now slightly more complicated, because there's more ways something that is wrong can be wrong, resulting either in code that fails at runtime rather than compile-time or less useful error messages.

人们已经发现围绕推理的某些情况令人困惑,这表明添加另一种复杂情况将无济于事.

That people already find some cases around inference to be confusing would point to the idea that adding another complicating case would not be helpful.

这并不是说这绝对不是一个好主意,只是出于利弊考虑,而不是明显的不足.

Which isn't to say that it is definitely a bad idea, just that there are pros and cons that make it a matter of opinion, rather than an obvious lack.

这篇关于用两个通用类型参数推断通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:16