C# 反模式

发布于 2024-08-06 20:29:30 字数 1597 浏览 5 评论 0原文

长话短说:我发现 Java 反模式 是不可或缺的资源。对于初学者和专业人士来说都是如此。我还没有为 C# 找到类似的东西。因此,我将把这个问题作为社区维基开放,并邀请每个人分享他们的知识。由于我是 C# 新手,我对此非常感兴趣,但无法从一些反模式开始:/

以下是我发现特别适用于 C# 而不是其他语言的答案。

我只是复制/粘贴这些!也考虑看看这些评论。


抛出 NullReferenceException

抛出错误的异常:

if (FooLicenceKeyHolder == null)
    throw new NullReferenceException();

属性与公共变量

类中的公共变量 (使用属性代替)。

除非该类是一个简单的数据传输对象。


不理解 bool 是一种真实类型,而不仅仅是一种约定

if (myBooleanVariable == true)
{
    ...
}

或者甚至更好的

if (myBooleanVariable != false)
{
    ...
}

像这样的构造C 和 C++ 开发人员经常使用布尔值的概念(0 == false,其他均为 true);这在 C# 或其他具有实数布尔值的语言中是不必要的(或不需要的)。


使用 using()

不使用 using< /code> 在适当的情况下:

object variable;
variable.close(); //Old code, use IDisposable if available.
variable.Dispose(); //Same as close.  Avoid if possible use the using() { } pattern.
variable = null; //1. in release optimised away.  2. C# is GC so this doesn't do what was intended anyway.

To cut a long story short: I find the Java antipatterns an indispensable resource. For beginners as much as for professionals. I have yet to find something like this for C#. So I'll open up this question as community wiki and invite everyone to share their knowledge on this. As I am new to C#, I am strongly interested in this, but cannot start with some antipatterns :/

Here are the answers which I find specifically true for C# and not other languages.

I just copy/pasted these! Consider throwing a look on the comments on these as well.


Throwing NullReferenceException

Throwing the wrong exception:

if (FooLicenceKeyHolder == null)
    throw new NullReferenceException();

Properties vs. public Variables

Public variables in classes (use a property instead).

Unless the class is a simple Data Transfer Object.


Not understanding that bool is a real type, not just a convention

if (myBooleanVariable == true)
{
    ...
}

or, even better

if (myBooleanVariable != false)
{
    ...
}

Constructs like these are often used by C and C++ developers where the idea of a boolean value was just a convention (0 == false, anything else is true); this is not necessary (or desirable) in C# or other languages that have real booleans.


Using using()

Not making use of using where appropriate:

object variable;
variable.close(); //Old code, use IDisposable if available.
variable.Dispose(); //Same as close.  Avoid if possible use the using() { } pattern.
variable = null; //1. in release optimised away.  2. C# is GC so this doesn't do what was intended anyway.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(30

北渚 2024-08-13 20:29:30

错误地重新抛出异常。重新抛出异常:

try
{
    // do some stuff here
}
catch (Exception ex)
{
    throw ex;  // INCORRECT
    throw;     // CORRECT
    throw new Exception("There was an error"); // INCORRECT
    throw new Exception("There was an error", ex); // CORRECT
}

Rethrowing the exception incorrectly. To rethrow an exception :

try
{
    // do some stuff here
}
catch (Exception ex)
{
    throw ex;  // INCORRECT
    throw;     // CORRECT
    throw new Exception("There was an error"); // INCORRECT
    throw new Exception("There was an error", ex); // CORRECT
}
月寒剑心 2024-08-13 20:29:30

GC.Collect() 来收集而不是信任垃圾收集器。

GC.Collect() to collect instead of trusting the garbage collector.

于我来说 2024-08-13 20:29:30

我在 Java 和 C# 中看到太多这种方式...

if(something == true){
  somethingelse = true;
}

如果它也有的话,会加分

else{
  somethingelse = false;
}

I see this one way too much, both in Java and C#...

if(something == true){
  somethingelse = true;
}

with bonus points if it also has

else{
  somethingelse = false;
}
棒棒糖 2024-08-13 20:29:30
using Microsoft.SharePoint;

'努夫说

using Microsoft.SharePoint;

'nuff said

送君千里 2024-08-13 20:29:30

我经常看到以下代码:

if (i==3)
       return true;
else
       return false;

应该是:

       return (i==3);

I see following code a lot:

if (i==3)
       return true;
else
       return false;

should be:

       return (i==3);
戏舞 2024-08-13 20:29:30

侮辱德墨忒尔法则:

a.PropertyA.PropertyC.PropertyB.PropertyE.PropertyA = 
     b.PropertyC.PropertyE.PropertyA;

Insulting the law of Demeter:

a.PropertyA.PropertyC.PropertyB.PropertyE.PropertyA = 
     b.PropertyC.PropertyE.PropertyA;
┈┾☆殇 2024-08-13 20:29:30

抛出NullReferenceException

if (FooLicenceKeyHolder == null)
    throw new NullReferenceException();

Throwing NullReferenceException:

if (FooLicenceKeyHolder == null)
    throw new NullReferenceException();
北座城市 2024-08-13 20:29:30

这是真的,我亲眼所见。

public object GetNull()
{
     return null;
}

它实际上在应用程序中使用,甚至还有一个与之配套的存储过程,一个会返回 null 的 sp_GetNull...

这让我很高兴。

我认为 sp 用于经典的 asp 站点.. 与结果集有关。 .net 是有人将代码“转换”为 .net 的想法...

This is true I seen it with my own eyes.

public object GetNull()
{
     return null;
}

It was actually used in the app, and even had a stored procedure to go with it too, an sp_GetNull that would return null....

that made my day.

I think the sp was used for a classic asp site .. something to do with a result set. the .net one was someone idea of "converting" the code into .net...

酒解孤独 2024-08-13 20:29:30
int foo = 100;
int bar = int.Parse(foo.ToString());

或者更一般的情况:

object foo = 100;
int bar = int.Parse(foo.ToString());
int foo = 100;
int bar = int.Parse(foo.ToString());

Or the more general case:

object foo = 100;
int bar = int.Parse(foo.ToString());
画尸师 2024-08-13 20:29:30

我在我们的项目中发现了这个,差点把椅子弄坏了......

DateTime date = new DateTime(DateTime.Today.Year, 
                             DateTime.Today.Month, 
                             DateTime.Today.Day);

I have found this in our project and almost broke the chair...

DateTime date = new DateTime(DateTime.Today.Year, 
                             DateTime.Today.Month, 
                             DateTime.Today.Day);
哽咽笑 2024-08-13 20:29:30

我经常遇到这种 var 滥用:

var ok = Bar();

甚至更好:

var i = AnyThing();

以这种方式使用 var 没有任何意义,也没有任何收获。它只会使代码更难遵循。

Quite often I stumble over this kind of var-abuse:

var ok = Bar();

or even better:

var i = AnyThing();

Using var that way makes no sense and gains nothing. It just makes the code harder to follow.

总攻大人 2024-08-13 20:29:30
不羁少年 2024-08-13 20:29:30

不理解 bool 是一种真实类型,而不仅仅是一种约定

if (myBooleanVariable == true)
{
    ...
}

,甚至更好。

if (myBooleanVariable != false)
{
    ...
}

CC++ 开发人员经常使用这样的构造,其中布尔值的想法是只是一个约定(0 == false,其他都是 true);这在 C# 或其他具有实数布尔值的语言中是不必要的(或不需要的)。

更新:重新表述最后一段以提高其清晰度。

Not understanding that bool is a real type, not just a convention

if (myBooleanVariable == true)
{
    ...
}

or, even better

if (myBooleanVariable != false)
{
    ...
}

Constructs like these are often used by C and C++ developers where the idea of a boolean value was just a convention (0 == false, anything else is true); this is not necessary (or desirable) in C# or other languages that have real booleans.

Updated: Rephrased the last paragraph to improve its clarity.

倒带 2024-08-13 20:29:30

类中的公共变量(改为使用属性)。

除非该类是一个简单的数据传输对象。

请参阅下面的评论以进行讨论和说明。

Public variables in classes (use a property instead).

Unless the class is a simple Data Transfer Object.

See comments below for discussion and clarification.

后知后觉 2024-08-13 20:29:30

我确实见过这个。

bool isAvailable = CheckIfAvailable();
if (isAvailable.Equals(true))
{ 
   //Do Something
}

轻松击败 isAvailable == true 反模式!
使其成为超级反模式!

I have actually seen this.

bool isAvailable = CheckIfAvailable();
if (isAvailable.Equals(true))
{ 
   //Do Something
}

beats the isAvailable == true anti-pattern hands down!
Making this a super-anti-pattern!

一张白纸 2024-08-13 20:29:30
object variable;
variable.close(); //Old code, use IDisposable if available.
variable.Dispose(); //Same as close.  Avoid if possible use the using() { } pattern.
variable = null; //1. in release optimised away.  2. C# is GC so this doesn't do what was intended anyway.
object variable;
variable.close(); //Old code, use IDisposable if available.
variable.Dispose(); //Same as close.  Avoid if possible use the using() { } pattern.
variable = null; //1. in release optimised away.  2. C# is GC so this doesn't do what was intended anyway.
脱离于你 2024-08-13 20:29:30

私有自动实现的属性:

private Boolean MenuExtended { get; set; }

Private auto-implemented properties:

private Boolean MenuExtended { get; set; }
执笔绘流年 2024-08-13 20:29:30

在每个方法的顶部声明和初始化所有局部变量是如此丑陋!

void Foo()
{
    string message;
    int i, j, x, y;
    DateTime date;

    // Code
}

Declaring and initializing all local variables at the top of each method is so ugly!

void Foo()
{
    string message;
    int i, j, x, y;
    DateTime date;

    // Code
}
┾廆蒐ゝ 2024-08-13 20:29:30

两个字符串反模式
反模式#1
检查字符串是否为 null 或空

//Bad
if( myString == null || myString == "" )
OR
if( myString == null || myString.Length == 0 )

//Good
string.IsNullOrEmpty(myString)

反模式 #2(仅适用于 .NET 4.0)
检查字符串是否为空、空白或空格

//Bad
if( myString == null || myString == "" || myString.Trim() == "")

//Good
string.IsNullOrWhiteSpace(myString) 

Two string anti patterns
Anti-Pattern # 1
Checking strings for null or empty

//Bad
if( myString == null || myString == "" )
OR
if( myString == null || myString.Length == 0 )

//Good
string.IsNullOrEmpty(myString)

Anti-Pattern # 2 (only for .NET 4.0)
Checking strings for null or empty or white space

//Bad
if( myString == null || myString == "" || myString.Trim() == "")

//Good
string.IsNullOrWhiteSpace(myString) 
柠栀 2024-08-13 20:29:30

无需强制转换(请相信编译器):

foreach (UserControl view in workspace.SmartParts)
{
  UserControl userControl = (UserControl)view;
  views.Add(userControl);
}

Needless casting (please trust the compiler):

foreach (UserControl view in workspace.SmartParts)
{
  UserControl userControl = (UserControl)view;
  views.Add(userControl);
}
表情可笑 2024-08-13 20:29:30
if(data != null)
{
  variable = data;
}
else
{
  variable = new Data();
}

可以更好地编写为

variable = (data != null) ? data : new Data();

,甚至更好地编写为

variable = data ?? new Data();

最后一个代码清单适用于 .NET 2.0 及更高版本

if(data != null)
{
  variable = data;
}
else
{
  variable = new Data();
}

can be better written as

variable = (data != null) ? data : new Data();

and even better written as

variable = data ?? new Data();

Last code listing works in .NET 2.0 and above

苯莒 2024-08-13 20:29:30

说话带着口音总是让我着迷。

C++ 程序员:

if (1 == variable) { }

在 C# 中,如果您输入 if (1=variable),这会给您带来编译器错误,这样您就可以按照您的意思编写代码,而不必担心自己会被射中。脚。

Speaking with an accent always caught me.

C++ programmers:

if (1 == variable) { }

In C# this will give you a compiler error if you were to type if (1 = variable), allowing you to write the code the way you mean it instead of worrying about shooting yourself in the foot.

另类 2024-08-13 20:29:30

不使用三元是我看到转换为 c# 的东西,偶尔

你会看到:

private string foo = string.Empty;
if(someCondition)
  foo = "fapfapfap";
else
  foo = "squishsquishsquish";

而不是:

private string foo  = someCondition ? "fapfapfap" : "squishsquishsquish";

Not using ternary's is something I see converts to c# do occasionally

you see:

private string foo = string.Empty;
if(someCondition)
  foo = "fapfapfap";
else
  foo = "squishsquishsquish";

instead of:

private string foo  = someCondition ? "fapfapfap" : "squishsquishsquish";
未央 2024-08-13 20:29:30

访问修改后的闭包

foreach (string list in lists)
{
        Button btn = new Button();
        btn.Click += new EventHandler(delegate { MessageBox.Show(list); });
}

(请参阅链接以获取说明和修复)

Accessing modified closures

foreach (string list in lists)
{
        Button btn = new Button();
        btn.Click += new EventHandler(delegate { MessageBox.Show(list); });
}

(see link for explanation and fix)

乖乖 2024-08-13 20:29:30

用于使用字符串连接而不是字符串生成器来连接任意数量的

字符串

foreach (string anItem in list)
    message = message + anItem;

For concating arbitrary number of strings using string concatenation instead of string builder

Exampls

foreach (string anItem in list)
    message = message + anItem;
各空 2024-08-13 20:29:30

这被认为是普遍的吗?

public static main(string [] args)
{
  quit = false;
  do
  {
  try
  {
      // application runs here .. 
      quit = true;
  }catch { }
  }while(quit == false);
}

我不知道如何解释它,但这就像有人捕获异常并一遍又一遍地重试代码,希望它以后能正常工作。就像如果发生 IOException 一样,他们只是一遍又一遍地尝试,直到它起作用为止。

is this considered general ?

public static main(string [] args)
{
  quit = false;
  do
  {
  try
  {
      // application runs here .. 
      quit = true;
  }catch { }
  }while(quit == false);
}

I dont know how to explain it, but its like someone catching an exception and retrying the code over and over hoping it works later. Like if a IOException occurs, they just try over and over until it works..

沫雨熙 2024-08-13 20:29:30

我所在的项目有五十个类,全部继承自同一个类,全部都定义了:

public void FormatZipCode(String zipCode) { ... }

要么将其放在父类中,要么将实用程序类放在一边。啊。

您是否考虑过浏览The Daily WTF

The project I'm on had fifty classes, all inheriting from the same class, that all defined:

public void FormatZipCode(String zipCode) { ... }

Either put it in the parent class, or a utility class off to the side. Argh.

Have you considered browsing through The Daily WTF?

我要还你自由 2024-08-13 20:29:30

过于复杂的“Page_Load”方法,想要完成所有事情。

Massively over-complicated 'Page_Load' methods, which want to do everything.

波浪屿的海角声 2024-08-13 20:29:30

使用属性除了简单地检索值或可能进行廉价计算之外,还可以用于其他任何用途。如果您从属性访问数据库,则应将其更改为方法调用。开发人员预计方法调用的成本可能很高,但他们不希望属性出现这种情况。

Using properties for anything other than to simply retrieve a value or possibly an inexpensive calculation. If you are accessing a database from your property, you should change it to a method call. Developers expect that method calls might be costly, they don't expect this from properties.

满天都是小星星 2024-08-13 20:29:30

在我继承的系统中发现了几次......

if(condition){
  some=code;
}
else
{
  //do nothing
}

反之亦然

if(condition){
  //do nothing
}
else
{
  some=code;
}

Found this a few times in a system I inherited...

if(condition){
  some=code;
}
else
{
  //do nothing
}

and vice versa

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