C#:全局别名通用类名?

发布于 2024-12-06 17:55:48 字数 436 浏览 0 评论 0原文

在某些项目中,我们使用泛型,我们得到很多这样的行:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一个人的旅程 2024-12-13 17:55:48

没有全局别名之类的东西。您可以做的是使用类型推断来简化您的声明:

var myLine = (Line<SomeTClass, SomeCClass>)LineFactory.CreateLine(...);

如果这对于推断系统来说不够具体,您可以使 CreateLine() 方法通用以强制执行它:

var myLine = LineFactory.CreateLine<Line<SomeTClass, SomeCClass>>(...);

并给出 LineFactory 类型的名称,甚至可以简化它更多:

var myLine = LineFactory.CreateLine<SomeTClass, SomeCClass>(...);

最后一个选项对我来说感觉“正确”,但在某种程度上我无法完全清楚地表达出来。以防万一您需要一些帮助,方法声明将如下所示:

public static class LineFactory 
{
    public static Line<T,C> CreateLine<T,C>(...) { ... }
}

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(...);

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>>(...);

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>(...) { ... }
}
物价感观 2024-12-13 17:55:48

不,您不能创建全局别名。

No, you cannot create a global alias.

北恋 2024-12-13 17:55:48

这可以通过添加一个文件来实现,例如带有以下声明的 GlobalUsings.cs

global using X = Full.Namespace.Line<SomeTClass,SomeCClass>;

如果更有意义,您还可以将其添加到项目中现有文件的顶部。

This is possible by adding a file, for example GlobalUsings.cs with the following declaration:

global using X = Full.Namespace.Line<SomeTClass,SomeCClass>;

You can also add it to the top of an existing file in your project if that makes more sense.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文