C#:为通用类名全局别名? [英] C#: Globally alias a generic class name?
问题描述
在某些项目中,我们使用的是泛型,我们得到很多类似这样的行:
in some project we are using Generics, and we get a lot of lines like this:
Line<SomeTClass,SomeCClass> myLine =
(Line<SomeTClass,SomeCClass>)LineFactory.CreateLine(...)
我们可以使用X = Line< SomeTClass,SomeCClass> 声明。
We can declare local alias, with using X = Line<SomeTClass,SomeCClass>
.
然后我们可以写, X myLine =(X)LineFactory.CreateLine(...)
。
我们有很多组合< T,C>
的值,但我们经常使用相同的值。是否有可能在全局范围内取消声明using,以便我们不必在每个文件中声明别名?
We have a lot a combination of <T,C>
but we often use the same. Is it possible de declare the using globally, so that we won't have to declare the alias in each file?
推荐答案
否例如全局别名。您可以使用类型推断来简化声明:
No such thing as a global alias. What you can do is use type inference to simplify your declarations:
var myLine = (Line<SomeTClass, SomeCClass>)LineFactory.CreateLine(...);
如果对于推理系统而言不够具体,则可以使CreateLine()方法通用为强制执行:
and if that's not specific enough for the inference system, you can make the CreateLine() method generic to enforce it:
var myLine = LineFactory.CreateLine<Line<SomeTClass, SomeCClass>>(...);
给定LineFactory类型的名称,甚至可以简化一下:
and given the name of the LineFactory type, maybe even simplify it some more:
var myLine = LineFactory.CreateLine<SomeTClass, SomeCClass>(...);
最后一种选择对我来说是一种正确的感觉,我无法完全表达出来。以防万一您需要一点帮助,方法声明看起来像这样:
This last option feels "right" to me in some way I can't fully articulate. Just in case you need a little help, the method declaration would look like something this:
public static class LineFactory
{
public static Line<T,C> CreateLine<T,C>(...) { ... }
}
这篇关于C#:为通用类名全局别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!