有没有一种方法可以缩短C#中的字段声明?

时间:2020-03-15 00:24:39

标签: c# new-operator

我为什么要写:

public VeryLongClassNameThatHurtsMyEyes<AnotherVeryLongClassName> field = new VeryLongClassNameThatHurtsMyEyes<AnotherVeryLongClassName>();

代替:

public var field = new VeryLongClassNameThatHurtsMyEyes<AnotherVeryLongClassName>();

有什么办法可以缩短这个荒谬的声明? 为什么我必须在一行中写两个相同类型?

已更新。 我发现使用“ dynamic”关键字而不是“ var”可以完美解决此问题! 请随时提供有关此解决方案性能(或其他)问题的任何信息!

1 个答案:

答案 0 :(得分:1)

您可以使用类型别名。可以找到文档here。链接到通用类的别名:here

using YourShortName = VeryLongClassNameThatHurtsMyEyes<AnotherVeryLongClassName>;

用法

public YourShortName field = new YourShortName();

有关为什么只能对局部变量使用var的信息,请参见here

然后see here深入研究dynamic以及为什么它甚至不能远距离使用var