C#新的'Classname'和默认值('classname')之间有什么区别

时间:2017-05-23 02:30:30

标签: c#

我是C#的新手并不熟悉它。我对new PostpaidProfile();default(AutoliftResult);的区别感到困惑。我的意思是它们的调用方式有何不同。下面是我不知道的类或对象是什么叫

public class PostpaidProfile
    {

        public bool WasRetrieved { get; set; }

        public string AccountCategory { get; set; }

        public string AccountNum { get; set; }

        public string Acd { get; set; }

        public string ActivationDate { get; set; }

        public int? AgingDays { get; set; }

        public decimal? CreditRating { get; set; }

        public string CutOff { get; set; }

        public string Cycle { get; set; }

        public bool? IsBlacklisted { get; set; }

        public bool? IsNopsa { get; set; }

        public decimal? Msf { get; set; }

        public string RatePlan { get; set; }

        public string ServiceStatus { get; set; }

        public int? VipCode { get; set; }

        public string Zip { get; set; }

        public string Remarks { get; set; }

    }

    public class AutoliftResult
    {

        public bool IsSuccess { get; set; }

        public decimal StatusCode { get; set; }

        public string Message { get; set; }

        public string SRNumber { get; set; }

    }

以及它们如何被称为

PostpaidProfile output = new PostpaidProfile();

AutoliftResult output = default(AutoliftResult);

我的问题是他们的区别是什么? (我不是在谈论他们的内容)如果我宣布AutoliftResult output = new AutoliftResult();

,它是一样的

2 个答案:

答案 0 :(得分:6)

new PostpaidProfile()创建一个新的类实例。

default(AutoliftResult)为指定的类型创建默认值。对于参考类型,它是null。对于值类型,通常是0转换为类型的任何内容 - 即,如果类型为int,则默认值为0;如果type为bool,则默认值为false等。

答案 1 :(得分:2)

  

默认关键字将为引用类型返回null,为数值类型返回零。

请注意,对于数值类型而不是所有值类型,它将返回零。例如,对于struct类型,即使它们是值类型,它也将返回结构的名称而不是零。请参阅小提琴here

在您的情况下,PostpaidProfile output = new PostpaidProfile()将返回一个实例,default将返回null。

如果这样做,将导致异常,因为output为空:

AutoliftResult output = default(AutoliftResult);
output.IsSuccess; // will not work

更多信息here

相关问题