首页 > 解决方案 > 隐式转换

问题描述

我正在尝试转换我班级的一个属性,但我总是遇到同样的错误

“用户定义的转换必须从或转换为分隔符类型”

public class CharCashItemOutputBoxEntity : BaseEntity
{
    public int Owner { get; set; }
    public string Kind { get; set; }
    public string RecId { get; set; }
    public int Amount { get; set; }
    public string StrChargeNo { get; set; }
    public int Deleted { get; set; }
    public DateTime CreateDate { get; set; }
    public DateTime? DeleteDate { get; set; }
    public string GaveCharName { get; set; }
    public int Confirm { get; set; }
    public int Period { get; set; }
    public int Price { get; set; }
    public string EvPtype { get; set; }
    public string Comment { get; set; }

    public static implicit operator long(BaseEntity baseEntity)
    {
        return baseEntity.Id;
    }
}

有谁知道它可能是什么?

标签: c#

解决方案


您需要将隐式转换移动到基类中,因为源类型必须与定义它的类相同。

例如,考虑以下具有两个类的代码。每个都有自己从包含类型的隐式转换。

public class BaseEntity
{
    public long Id { get; set; }

    public static implicit operator long(BaseEntity baseEntity)
    {
        return baseEntity.Id;
    }
}

public class CharCashItemOutputBoxEntity : BaseEntity
{
    public int Owner { get; set; }
    public string Kind { get; set; }
    public string RecId { get; set; }
    public int Amount { get; set; }
    public string StrChargeNo { get; set; }
    public int Deleted { get; set; }
    public DateTime CreateDate { get; set; }
    public DateTime? DeleteDate { get; set; }
    public string GaveCharName { get; set; }
    public int Confirm { get; set; }
    public int Period { get; set; }
    public int Price { get; set; }
    public string EvPtype { get; set; }
    public string Comment { get; set; }

    public static implicit operator string(CharCashItemOutputBoxEntity entity)
    {
        return entity.RecId;
    }
}

带有示例代码

var entity = new CharCashItemOutputBoxEntity();

long id = entity;
string recId = entity;

推荐阅读