初始化C#自动性能 [英] Initializing C# auto-properties

查看:113
本文介绍了初始化C#自动性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经习惯了写作课是这样的:

 公共类Foo {
  私人字符串毫巴=酒吧;
  公共字符串酒吧{
    {返回毫巴; }
    集合{毫巴=价值; }
  }
  // ...其他的方法,没有构造...
}

转换杆到自动属性看起来很方便,简洁,但我怎么能留住初始化而不添加一个构造函数,并把初始化在那里呢?

 公共类foo2theRevengeOfFoo {
  //私人字符串毫巴=酒吧;
  公共字符串酒吧{搞定;组; }
  // ...其他的方法,没有构造...
  //行为发生了变化。
}

您可以看到,添加一个构造函数是不是用心血积蓄我应该从汽车的属性会得到内联。

这样的事情会让我更有意义:

 公共字符串酒吧{搞定;组; } =栏;


解决方案

更​​新 - 低于前C#6写着答案来了。在C#6你可以写:

 公共类Foo
{
    公共字符串酒吧{搞定;组; } =栏;
}

您可以的写只读自动实现的属性,只是在构造函数中写入(但也可以赋予一个默认的初始值:

 公共类Foo
{
    公共字符串酒吧{搞定; }    公共美孚(串吧)
    {
        酒吧=杆;
    }
}


这是不幸的,有没有现在这样做的方式。你必须设置在构造函数的值。 (使用构造函数链可以帮助避免重复。)

自动实现的属性是很方便的权利,但肯定会是更好。我不觉得自己经常想这种初始化因为这只能在构造函数中设置,并将由一个只读字段来支持只读自动实现属性。

这并没有发生,直到并包括C#5,但正在计划中的C#6 - 无论是在允许初始化在声明的角度而言,的允许只读自动实现属性在构造函数体内被初始化。

I'm used to writing classes like this:

public class foo {
  private string mBar = "bar";
  public string Bar {
    get { return mBar; }
    set { mBar = value; }
  }
  //... other methods, no constructor ...
}

Converting Bar to an auto-property seems convenient and concise, but how can I retain the initialization without adding a constructor and putting the initialization in there?

public class foo2theRevengeOfFoo {
  //private string mBar = "bar";
  public string Bar { get; set; }
  //... other methods, no constructor ...
  //behavior has changed.
}

You could see that adding a constructor isn't inline with the effort savings I'm supposed to be getting from auto-properties.

Something like this would make more sense to me:

public string Bar { get; set; } = "bar";

解决方案

Update - the answer below was written before C# 6 came along. In C# 6 you can write:

public class Foo
{
    public string Bar { get; set; } = "bar";
}

You can also write read-only automatically-implemented properties, which are only writable in the constructor (but can also be given a default initial value:

public class Foo
{
    public string Bar { get; }

    public Foo(string bar)
    {
        Bar = bar;
    }
}


It's unfortunate that there's no way of doing this right now. You have to set the value in the constructor. (Using constructor chaining can help to avoid duplication.)

Automatically implemented properties are handy right now, but could certainly be nicer. I don't find myself wanting this sort of initialization as often as a read-only automatically implemented property which could only be set in the constructor and would be backed by a read-only field.

This hasn't happened up until and including C# 5, but is being planned for C# 6 - both in terms of allowing initialization at the point of declaration, and allowing for read-only automatically implemented properties to be initialized in a constructor body.

这篇关于初始化C#自动性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆