C#:全局别名通用类名?
在某些项目中,我们使用泛型,我们得到很多这样的行:
Line<SomeTClass,SomeCClass> myLine =
(Line<SomeTClass,SomeCClass>)LineFactory.CreateLine(...)
我们可以声明本地别名,使用using X = Line
。
然后我们可以编写,X myLine = (X)LineFactory.CreateLine(...)
。
我们有很多
的组合,但我们经常使用相同的组合。是否可以全局声明 using ,这样我们就不必在每个文件中声明别名?
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(...)
We can declare local alias, with using X = Line<SomeTClass,SomeCClass>
.
Then we can write, X myLine = (X)LineFactory.CreateLine(...)
.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有全局别名之类的东西。您可以做的是使用类型推断来简化您的声明:
如果这对于推断系统来说不够具体,您可以使 CreateLine() 方法通用以强制执行它:
并给出 LineFactory 类型的名称,甚至可以简化它更多:
最后一个选项对我来说感觉“正确”,但在某种程度上我无法完全清楚地表达出来。以防万一您需要一些帮助,方法声明将如下所示:
No such thing as a global alias. What you can do is use type inference to simplify your declarations:
and if that's not specific enough for the inference system, you can make the CreateLine() method generic to enforce it:
and given the name of the LineFactory type, maybe even simplify it some more:
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:
不,您不能创建全局别名。
No, you cannot create a global alias.
这可以通过添加一个文件来实现,例如带有以下声明的
GlobalUsings.cs
:如果更有意义,您还可以将其添加到项目中现有文件的顶部。
This is possible by adding a file, for example
GlobalUsings.cs
with the following declaration:You can also add it to the top of an existing file in your project if that makes more sense.