在C#3自动属性 ​​- 必须声明一个机构得到,如果我宣布一个用于设置? [英] Automatic Properties in C# 3 - Must declare a body for get if I declare one for set?

查看:150
本文介绍了在C#3自动属性 ​​- 必须声明一个机构得到,如果我宣布一个用于设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用VS 2008,并在我的属性页的项目,我看到,我针对的.Net 3.5。

I'm using VS 2008, and in my property pages for the project I see that I'm targeting .Net 3.5.

下面是我在编译的时候得到的错误:

Here is the error I'm getting when trying to compile:

AMSDataModels.Vehicle.VIN.get必须声明主体,因为它不标记为abstract,EXTERN或部分

AMSDataModels.Vehicle.VIN.get' must declare a body because it is not marked abstract, extern, or partial

这里是code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AMSDataModels
{
    public class Vehicle
    {
        //NodeID for datastore persistance
        public Guid NodeID { get; set; }

        public string VIN { get; 
            set { 
                if (value.Length != 17) throw new ArgumentOutOfRangeException("VIN", "VIN must be 17 characters"); 
            } }

        public string Make { get; set; }
        public string Model { get; set; }
    }
}

如果我脱光全身的集合,这样它只是:

If I strip the body from set so that its just:

public string VIN { get; set; }

所有的作品,但我失去了我的能力来检查VIN,因为它被设定。

All works, but I lose my ability to check the VIN as it is set.

没有任何人有一个如何解决这个问题的建议或更好的方式来处理手头的问题?

Does anyone have a suggestion of how to fix this or a better way to approach the problem at hand?

我真的很喜欢速记符号 - 但验证输入的合法性也很重要

I really like the shorthand notation - but verifying the legitimacy of input is important too!

推荐答案

如果您要添加逻辑设定,你需要将其添加到拿到为好。在您所设定的注意,你实际上并没有设置一个值什么?

If you're going to add logic in the set, you need to add it into the get as well. Notice in your set you're not actually setting a value to anything?

添加一个后备字段,

private string _vin;

和返回,在搞定。

public string VIN
{
    get { return _vin; }
    set
    {
      if (value.Length != 17) 
        throw new ArgumentOutOfRangeException("VIN", "VIN must be 17 characters"); 
      else
        _vin = value;
    }
}

这篇关于在C#3自动属性 ​​- 必须声明一个机构得到,如果我宣布一个用于设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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