带逻辑的C#Private Setter

时间:2015-06-06 17:42:09

标签: c#

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

namespace Crystal_Message
{
    class Person
    {
        private string firstName="";
        private string lastName= "";
        private string phone="";


        public Person(string firstName, string lastName, string phone)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
            this.PhoneNumber = phone;


        }

        public string FirstName
        {
            get { return firstName; }

            set
            {
                if (string.IsNullOrWhiteSpace(this.firstName)){

                    throw new ArgumentNullException("Must Include First Name");
                }

                this.firstName = value;
            }

        }

        public string LastName
        {
            get { return lastName; }

            set
            {
                if (string.IsNullOrWhiteSpace(lastName)){

                    throw new ArgumentNullException("Must Include Last Name");
                }

                this.lastName = value;
            }

        }

        public string PhoneNumber
        {
            get { return phone; }

            set
            {
                if (string.IsNullOrWhiteSpace(phone)){

                    throw new ArgumentNullException("Must Include Phone Number");
                }

                this.phone = value;
            }

        }


        public override string ToString()
        {
            return "First Name: " + this.FirstName + " " + " Last Name: " + this.LastName + " Phone Number: " + this.PhoneNumber;
        }


    }
}

我有一个简单的人类,它带有名字,姓氏和电子邮件。它适用于我,它不会被分类。我正在构建一个小应用程序,而且这个人类很合适。

我唯一的问题是,如何使用内部逻辑实现私有 setter,以确保该值不为空或为空?

3 个答案:

答案 0 :(得分:3)

您可以为属性设置器使用私有修饰符:

public string FirstName
{
    get { return firstName; }

    private set
    {
        // Here you must check if value is not null or empty, not the field
        if (string.IsNullOrWhiteSpace(value)){
            throw new ArgumentNullException("Must Include First Name");
        }
        this.firstName = value;
    }
}

在这种情况下,只能从同一个类访问属性的setter。

答案 1 :(得分:3)

只将setter设为私有。另外,你有一个问题:

value

将读取现有的属性值。您应该检查新提供的string.IsNullOrWhiteSpace(value)

    public string LastName
    {
        get { return lastName; }

        private set
        {
            if (string.IsNullOrWhiteSpace(value)) {
                throw new ArgumentNullException("Must Include Last Name");
            }

            lastName = value;
        }
    }

最终代码:

package com.tlians.t_calculator;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {


Button add=(Button) findViewById(R.id.add);
Button sub=(Button) findViewById(R.id.sub);
Button times=(Button) findViewById(R.id.times);
Button div=(Button) findViewById(R.id.div);
EditText num1=(EditText) findViewById(R.id.num1);
EditText num2=(EditText) findViewById(R.id.num2);
TextView result=(TextView) findViewById(R.id.result);


public void calculate(char a){
    String N1=num1.getText().toString();
    String N2=num2.getText().toString();
    float n1=Float.parseFloat(N1);
    float n2=Float.parseFloat(N2);
    if(a=='+')
        result.setText(""+n1+n2);
    else if(a=='-')
        result.setText(""+(n1-n2));
    else if(a=='/')
        result.setText(""+n1/n2);
    else if(a=='*')
        result.setText(""+n1*n2);
    else
        result.setText("Tani has only assigned four functions right now.");

}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

        add.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v){
                calculate('+');
            }
        });
        sub.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v){
                calculate('-');
            }

        });
        times.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v){
                calculate('*');
            }
        });
        div.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v){
                calculate('/');
            }
        });


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

答案 2 :(得分:2)

有两种方法:

首先,你可以摆脱set,你的班级可以对基础价值进行操作:

public string FirstName
    {
        get { return firstName; }
    }
}

// Then in your code:
this.firstName = "whatever"; // the local variable

或者您可以将设置器的范围限定为private

public string FirstName
    {
        get { return firstName; }

        private set
        {
            if (string.IsNullOrWhiteSpace(this.firstName)){

                throw new ArgumentNullException("Must Include First Name");
            }

            this.firstName = value;
        }

    }
相关问题