如何在 C# 中为类名设置别名,而不必向使用该类的每个文件添加一行代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/244246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I alias a class name in C#, without having to add a line of code to every file that uses the class?
提问by Ian Boyd
i want to create an alias for a class name. The following syntax would be perfect:
我想为类名创建别名。以下语法将是完美的:
public class LongClassNameOrOneThatContainsVersionsOrDomainSpecificName
{
...
}
public class MyName = LongClassNameOrOneThatContainsVersionOrDomainSpecificName;
but it won't compile.
但它不会编译。
Example
例子
NoteThis example is provided for convience only. Don't try to solve this particular problem by suggesting changing the design of the entire system. The presence, or lack, of this example doesn't change the original question.
注意提供此示例仅为方便起见。不要试图通过建议更改整个系统的设计来解决这个特定问题。这个例子的存在或缺失不会改变最初的问题。
Some existing code depends on the presence of a static class:
一些现有代码取决于静态类的存在:
public static class ColorScheme
{
...
}
This color scheme is the Outlook 2003 color scheme. i want to introduce an Outlook 2007 color scheme, while retaining the Outlook 2003 color scheme:
此配色方案是 Outlook 2003 配色方案。我想介绍一个 Outlook 2007 配色方案,同时保留 Outlook 2003 配色方案:
public static class Outlook2003ColorScheme
{
...
}
public static class Outlook2007ColorScheme
{
...
}
But i'm still faced with the fact that the code depends on the presence of a static class called ColorScheme. My first thought was to create a ColorScheme class that i will descend from either Outlook2003 or Outlook2007:
但我仍然面临这样一个事实,即代码取决于一个名为 ColorScheme 的静态类的存在。我的第一个想法是创建一个 ColorScheme 类,我将从 Outlook2003 或 Outlook2007 派生:
public static class ColorScheme : Outlook2007ColorScheme
{
}
but you cannot descend from a static class.
但你不能从静态类下降。
My next thought was to create the static ColorScheme class, but make Outlook2003ColorScheme and Outlook2007ColorScheme classes non-static. Then a static variable in the static ColorScheme class can point to either "true" color scheme:
我的下一个想法是创建静态 ColorScheme 类,但使 Outlook2003ColorScheme 和 Outlook2007ColorScheme 类非静态。然后静态 ColorScheme 类中的静态变量可以指向任一“真”配色方案:
public static class ColorScheme
{
private static CustomColorScheme = new Outlook2007ColorScheme();
...
}
private class CustomColorScheme
{
...
}
private class Outlook2008ColorScheme : CustomColorScheme
{
...
}
private class Outlook2003ColorScheme : CustomColorScheme
{
...
}
but that would require me to convert a class composed entirly of readonly static Colors into overridable properties, and then my ColorScheme class would need to have the 30 different property getters thunk down into the contained object.
但这需要我将一个完全由只读静态颜色组成的类转换为可覆盖的属性,然后我的 ColorScheme 类需要将 30 个不同的属性 getter 转换为包含的对象。
That's just too much typing.
打字太多了。
So my next thought was to alias the class:
所以我的下一个想法是给这个类取别名:
public static ColorScheme = Outlook2007ColorScheme;
But that doesn't compile.
但这不能编译。
How can i alias a static class into another name?
如何将静态类别名为另一个名称?
Update:Can someone please add the answer "You cannot do this in C#", so i can mark that as the accepted answer. Anyone else wanting the answer to the same question will find this question, the accepted answer, and a number of workarounds that might, or might not, be useful.
更新:有人可以添加答案“您不能在 C# 中执行此操作”,以便我可以将其标记为已接受的答案。其他任何想要回答同一问题的人都会发现这个问题、已接受的答案以及一些可能有用也可能没有用的解决方法。
i just want to close this question out.
我只想结束这个问题。
采纳答案by Ian Boyd
You cannot alias a class name in C#.
您不能在 C# 中为类名设置别名。
There are things you can do that are not aliasing a class name in C#.
在 C# 中,您可以做一些不为类名设置别名的事情。
But to answer the original question: you cannot alias a class name in C#.
但是要回答最初的问题:您不能在 C# 中为类名设置别名。
Update:People are confused why using
doesn't work. Example:
更新:人们很困惑为什么using
不起作用。例子:
Form1.cs
表格1.cs
private void button1_Click(object sender, EventArgs e)
{
this.BackColor = ColorScheme.ApplyColorScheme(this.BackColor);
}
ColorScheme.cs
配色方案
class ColorScheme
{
public static Color ApplyColorScheme(Color c) { ... }
}
And everything works. Now i want to create a newclass, and aliasColorScheme
to it (so that no code needs to be modified):
一切正常。现在我想创建一个新类和它的别名ColorScheme
(这样不需要修改代码):
ColorScheme.cs
配色方案
using ColorScheme = Outlook2007ColorScheme;
class Outlook2007ColorScheme
{
public static Color ApplyColorScheme(Color c) { ... }
}
Ohh, i'm sorry. This code doesn't compile:
哦,对不起。此代码无法编译:
My question was how to aliasa class in C#. It cannot be done. There are things i can do that are notaliasing a class name in C#:
我的问题是如何在 C# 中为类设置别名。这是不可能的。我可以做的一些事情不会在 C# 中为类名设置别名:
- change everyone who depends on
ColorScheme
tousing
ColorScheme
instead (code change workaround because i cannot alias) - change everyone who depends on
ColorScheme
to use a factory pattern them a polymorphic class or interface (code change workaround because i cannot alias)
- 改变大家谁依赖于
ColorScheme
以using
ColorScheme
代替(代码变化的解决方法,因为我无法别名) - 将依赖于
ColorScheme
使用工厂模式的每个人更改为多态类或接口(代码更改解决方法,因为我不能使用别名)
But these workarounds involve breaking existing code: not an option.
但是这些变通方法涉及破坏现有代码:不是一个选项。
If people depend on the presence of a ColorScheme
class, i have to actually copy/paste a ColorScheme
class.
如果人们依赖于一个ColorScheme
类的存在,我必须实际复制/粘贴一个ColorScheme
类。
In other words: i cannot alias a class name in C#.
换句话说:我不能在 C# 中为类名设置别名。
This contrasts with other object oriented languages, where i could define the alias:
这与其他面向对象的语言形成对比,我可以在其中定义别名:
ColorScheme = Outlook2007ColorScheme
and i'd be done.
我就完了。
回答by Konrad Rudolph
If you change the original class name, you could rewrite the dependent code using an import alias as a typedef
substitute:
如果更改原始类名,则可以使用导入别名作为typedef
替代来重写依赖代码:
using ColorScheme = The.Fully.Qualified.Namespace.Outlook2007ColorScheme;
This has to go at the top of the file/namespace, just like regular using
s.
这必须位于文件/命名空间的顶部,就像常规using
s 一样。
I don't know if this is practical in your case, though.
不过,我不知道这在您的情况下是否实用。
回答by dpurrington
try this:
尝试这个:
using ColorScheme=[fully qualified].Outlook2007ColorScheme
回答by Chris Marasti-Georg
You want a (Factory|Singleton), depending on your requirements. The premise is to make it so that the client code doesn't have to know which color scheme it is getting. If the color scheme should be application wide, a singleton should be fine. If you may use a different scheme in different circumstances, a Factory pattern is probably the way to go. Either way, when the color scheme needs to change, the code only has to be changed in one place.
您需要一个(Factory| Singleton),具体取决于您的要求。前提是使客户端代码不必知道它正在获取哪种配色方案。如果配色方案应用广泛,单例应该没问题。如果您可能在不同的情况下使用不同的方案,那么工厂模式可能是您要走的路。无论哪种方式,当需要更改配色方案时,只需在一处更改代码。
public interface ColorScheme {
Color TitleBar { get; }
Color Background{ get; }
...
}
public static class ColorSchemeFactory {
private static ColorScheme scheme = new Outlook2007ColorScheme();
public static ColorScheme GetColorScheme() { //Add applicable arguments
return scheme;
}
}
public class Outlook2003ColorScheme: ColorScheme {
public Color TitleBar {
get { return Color.LightBlue; }
}
public Color Background {
get { return Color.Gray; }
}
}
public class Outlook2007ColorScheme: ColorScheme {
public Color TitleBar {
get { return Color.Blue; }
}
public Color Background {
get { return Color.White; }
}
}
回答by chills42
Is it possible to change to using an interface?
是否可以更改为使用接口?
Perhaps you could create an IColorScheme
interface that all of the classes implement?
也许您可以创建一个IColorScheme
所有类都实现的接口?
This would work well with the factory pattern as shown by Chris Marasti-Georg
如 Chris Marasti-Georg 所示,这将适用于工厂模式
回答by mohammedn
You can make an alias for your class by adding this line of code:
您可以通过添加以下代码行来为您的班级创建别名:
using Outlook2007ColorScheme = YourNameSpace.ColorScheme;
回答by Timothy
Aliasing the way that you would like to do it will not work in C#. This is because aliasing is done through the using
directive, which is limited to the file/namespace in question. If you have 50 files that use the old class name, that will mean 50 places to update.
以您想要的方式别名在 C# 中不起作用。这是因为别名是通过using
指令完成的,该指令仅限于有问题的文件/命名空间。如果您有 50 个使用旧类名的文件,则意味着有 50 个地方需要更新。
That said, I think there is an easy solution to make your code change as minimal as possible. Make the ColorScheme
class a facade for your calls to the actual classes with the implementation, and use the using
in that file to determine which ColorScheme
you use.
也就是说,我认为有一个简单的解决方案可以使您的代码更改尽可能少。使ColorScheme
该类成为您对具有实现的实际类的调用的外观,并使用该using
文件中的 来确定ColorScheme
您使用哪个。
In other words, do this:
换句话说,这样做:
using CurrentColorScheme = Outlook2007ColorScheme;
public static class ColorScheme
{
public static Color ApplyColorScheme(Color c)
{
return CurrentColorScheme.ApplyColorScheme(c);
}
public static Something DoSomethingElse(Param a, Param b)
{
return CurrentColorScheme.DoSomethingElse(a, b);
}
}
Then in your code behind, change nothing:
然后在你后面的代码中,什么都不做:
private void button1_Click(object sender, EventArgs e)
{
this.BackColor = ColorScheme.ApplyColorScheme(this.BackColor);
}
You can then update the values of ColorScheme
by updating one line of code (using CurrentColorScheme = Outlook2008ColorScheme;
).
然后,您可以ColorScheme
通过更新一行代码 ( using CurrentColorScheme = Outlook2008ColorScheme;
)来更新 的值。
A couple concerns here:
这里有几个问题:
- Every new method or property definition will then need to be added in two places, to the
ColorScheme
class and to theOutlook2007ColorScheme
class. This is extra work, but if this is true legacy code, it shouldn't be a frequent occurence. As a bonus, the code inColorScheme
is so simple that any possible bug is very obvious. - This use of static classes doesn't seem natural to me; I probably would try to refactor the legacy code to do this differently, but I understand too that your situation may not allow that.
- If you already have a
ColorScheme
class that you're replacing, this approach and any other could be a problem. I would advise that you rename that class to something likeColorSchemeOld
, and then access it throughusing CurrentColorScheme = ColorSchemeOld;
.
- 然后,每个新方法或属性定义都需要添加到两个地方,即
ColorScheme
类和Outlook2007ColorScheme
类。这是额外的工作,但如果这是真正的遗留代码,它不应该经常出现。作为奖励,中的代码ColorScheme
非常简单,任何可能的错误都非常明显。 - 静态类的这种使用对我来说似乎并不自然。我可能会尝试重构遗留代码以不同的方式执行此操作,但我也理解您的情况可能不允许这样做。
- 如果您已经有一个
ColorScheme
要替换的类,则这种方法和任何其他方法都可能有问题。我建议您将该类重命名为类似的名称ColorSchemeOld
,然后通过using CurrentColorScheme = ColorSchemeOld;
.
回答by percebus
I suppose you can always inherit from the base class with nothing added
我想你总是可以从基类继承而不添加任何东西
public class Child : MyReallyReallyLongNamedClass {}
UPDATE
更新
But if you have the capability of refactoring the class
itself: A class name is usually unnecessarily long due to lack of namespace
s.
但是如果你有重构class
自身的能力:由于缺少namespace
s,类名通常会不必要地长。
If you see cases as ApiLoginUser
, DataBaseUser
, WebPortalLoginUser
, is usually indication of lack of namespace
due the fear that the name User
might conflict.
如果您看到大小写为ApiLoginUser
, DataBaseUser
, WebPortalLoginUser
, 通常表示namespace
由于担心名称User
可能会发生冲突而缺乏。
In this case however, you can use namespace
alias ,as it has been pointed out in above posts
但是,在这种情况下,您可以使用namespace
alias ,正如在上面的帖子中指出的那样
using LoginApi = MyCompany.Api.Login;
using AuthDB = MyCompany.DataBase.Auth;
using ViewModels = MyCompany.BananasPortal.Models;
// ...
AuthDB.User dbUser;
using ( var ctxt = new AuthDB.AuthContext() )
{
dbUser = ctxt.Users.Find(userId);
}
var apiUser = new LoginApi.Models.User {
Username = dbUser.EmailAddess,
Password = "*****"
};
LoginApi.UserSession apiUserSession = await LoginApi.Login(apiUser);
var vm = new ViewModels.User(apiUserSession.User.Details);
return View(vm);
Note how the class
names are all User
, but in different namespace
s. Quoting PEP-20: Zen of Python:
请注意class
名称都是如何User
,但在不同的namespace
s 中。引用PEP-20:Python 之禅:
Namespaces are one honking great idea -- let's do more of those!
命名空间是一个很棒的想法——让我们做更多的事情!
Hope this helps
希望这可以帮助
回答by Mark Farmiloe
It's a very late partial answer - but if you define the same class 'ColorScheme', in the same namespace 'Outlook', but in separate assemblies, one called Outlook2003 and the other Outlook2007, then all you need to do is reference the appropriate assembly.
这是一个很晚的部分答案 - 但是如果您在同一个命名空间“Outlook”中定义了同一个类“ColorScheme”,但是在不同的程序集中,一个称为 Outlook2003 和另一个 Outlook2007,那么您需要做的就是引用适当的程序集.
回答by J-Americano
I'm adding this comment for users finding this long after OP accepted their "answer". Aliasing in C# works by specifying the class name using it's fully qualified namespace. One defined, the alias name can be used within it's scope. Example.
我正在为在 OP 接受他们的“答案”后很久发现这一点的用户添加此评论。C# 中的别名通过使用完全限定的命名空间指定类名来工作。一经定义,别名可在其范围内使用。例子。
using aliasClass = Fully.Qualified.Namespace.Example;
//Example being the class in the Fully.Qualified.Namespace
public class Test{
public void Test_Function(){
aliasClass.DoStuff();
//aliasClass here representing the Example class thus aliasing
//aliasClass will be in scope for all code in my Test.cs file
}
}
Apologies for the quickly typed code but hopefully it explains how this should be implemented so that users aren't mislead into believing it cannot be done in C#.
对快速输入的代码表示歉意,但希望它解释了应该如何实现,以便用户不会误认为它不能在 C# 中完成。