C#代码规范学习之基本类的构建(一)

3 篇文章 0 订阅

微软官方文档之基本类的构建
public class Customer: IComparable

{

// Used to control which field is used for comparisons.

private static CompareField m_CompareField;

public int Id;

public string Name;

public enum CompareField

{

    Name,

    Id

}

static Customer()

{

    // Set the default compare field

    m_CompareField = CompareField.Name;

}

public static void SetCompareKey(CompareField CompareKey)

{

    // Change the comparison field

    m_CompareField = CompareKey;

}

// Set default values by delegating to the next most complex constructor

public Customer():this(-1, "No Name")

{

}

public Customer(int newId, string newName)

{

    this.Id = newId;

    this.Name = newName;

}

public int CompareTo(object obj)

{

    // First check to make sure we're only being compared to another customer.

    if(obj.GetType().ToString() == "Customer")

    {

        // Create a strongly typed reference
         Customerc = (Customer) obj;

        // Determine if we should compare by Name or Id

        if (Customer.m_CompareField == CompareField.Name)

        {

            return string.Compare(c.Name, this.Name, false);

        }

        else 

        {

            if (c.Id == this.Id)

            {

                return 0;

            }


            else if (c.Id < this.Id)

            {

                return 1;

            }

            else 

            {

                return -1;

            }

        }

    }

    else 

    {

        throw new ArgumentException("Customers can only be compared against other customers. The object being passed in was a " + obj.GetType().ToString());

    }

}

public override string ToString()

{

    // Normally ToString returns the fully qualified typename.

    // We are overriding it so that we can return a simple

    // display string when we're added to a list box.

    return string.Format("Id={0}, Name={1}", this.Id, this.Name);

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SharlockYu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值