default(T);

在泛型类型中,由于泛型类型即可以是引用类型也可以是值类型,所以不能用null来表示默认值。这里通过default来进行。引用类型的default将泛型类型初始化null,值类型的default将泛型类型初始化为0。

之所以会用到default关键字,是因为需要在不知道类型参数为值类型还是引用类型的情况下,为对象实例赋初值。考虑以下代码:

class TestDefault<T>
    {
        public T foo()
        {
            T t = null; //???
            return t;
        }
    }

如果我们用int型来绑定泛型参数,那么T就是int型,那么注释的那一行就变成了 int t = null;显然这是无意义的。为了解决这一问题,引入了default关键字:

class TestDefault<T>
    {
        public T foo()
        {
                return default(T);
        }
    }

   [Serializable]
    public class ResponseBase
    {


        public ResponseBase()
        {
            Ok = true;
            Result = "Ok";
            Code = EStatusCode.Ok;
        }

        /// <summary>
        /// 默认状态
        /// </summary>
        public bool Ok { get; set; }

        /// <summary>
        /// 状态码
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        /// 异常说明;正常时为空
        /// </summary>
        public string Result { get; set; }

        /// <summary>
        /// 其它标签
        /// </summary>
        public string TagValue { get; set; }

        /// <summary>
        /// 当前第几页
        /// </summary>
        public int PageIndex { get; set; }

        /// <summary> 分页字符串
        /// </summary>
        public string PagingStr { get; set; }

        /// <summary>
        /// 共多少条数据
        /// </summary>
        public int PageSum { get; set; }
        /// <summary>
        /// 总个数
        /// </summary>
        public int TotalCount { get; set; }



        public int TempValue { get; set; }

    }

    [Serializable]
    /// <summary>
    /// 响应数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ServiceResponse<T> : ResponseBase
    {
        public ServiceResponse()
        {
            Data = default(T);
        }

        /// <summary>
        ///数据集合
        /// </summary>
        public T Data { get; set; }

    }



-----------------------------------------
 ServiceResponse<int> result = new ServiceResponse<int>();
            try
            {
                result.Data = stuIndexLearnBll.SubmitInterst(interst);
            }
            catch (Exception ex)
            {
                ErrorHelper.InsertLog(new ErrorMessage()
                {
                    UserId = interst.UserId,
                    CustomInfo = $"接口:SubmitInterst;参数 StuInterst:{JsonConvert.SerializeObject(interst)}",
                    MessageInfo = ex.Message,
                    StackTrace = ex.StackTrace
                }.ToObString());
                result.Code = EStatusCode.ErrorElse;
                result.Ok = false;
                result.Result = "";
            }
            return result;

 

posted @ 2019-12-11 14:37  哈根达斯  阅读(638)  评论(0编辑  收藏  举报