让我们以将“潜在客户”转换为“商机”的示例来理解这个问题。如果我们将“潜在客户”定义为
public class Lead
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
我们想将其转换为“Opportunity”。
public class Opportunity
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal Worth {get;set;}
}
映射与转换
为了实现这一点,我们需要创建一个新的Opportunity
实例,然后复制其值,因此我们创建了一个新的函数来完成这个任务,并且这个函数需要在一个class
中。
public Opportunity Convert(Lead lead)
{
Opportunity opp = new Opportunity();
opp.Id = lead.Id.ToString();
opp.FirstName = lead.FirstName;
opp.LastName = lead.LastName;
return opp;
}
所以我们将该方法移动到
Opportunity
类内部,并将其设为
static
,以便可以通过
Opportunity.Convert()
进行调用。
public class Opportunity
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal Worth {get;set;}
public static Opportunity Convert(Lead lead)
{
Opportunity opp = new Opportunity();
opp.Id = lead.Id.ToString();
opp.FirstName = lead.FirstName;
opp.LastName = lead.LastName;
return opp;
}
}
void Main()
{
Lead lead = new Lead();
lead.Id = Guid.NewGuid();
lead.FirstName = "Vinod";
lead.LastName = "Srivastv";
lead.Dump();
Opportunity opp = Opportunity.Convert(lead);
opp.Dump();
}
但是通过 explicit
和 implicit
我们可以声明转换操作符,这样就不需要调用 Opportunity
类的 Convert
方法。
implicit
示例
在 implicit
转换中,我们不需要手动进行对象强制转换,因为它会隐式地进行转换。
public class Opportunity
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal Worth {get;set;}
public static implicit operator Opportunity(Lead lead)
{
Opportunity opp = new Opportunity();
opp.Id = lead.Id.ToString();
opp.FirstName = lead.FirstName;
opp.LastName = lead.LastName;
return opp;
}
}
void Main()
{
Lead lead = new Lead();
lead.Id = Guid.NewGuid();
lead.FirstName = "Vinod";
lead.LastName = "Srivastv";
lead.Dump();
Opportunity opp = lead;
opp.Dump();
}
![enter image description here](https://istack.dev59.com/cL7m0.webp)
明确
示例
现在我们刚刚从上面的代码中将关键词从隐式更改为明确:
public class Opportunity
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal Worth {get;set;}
public static explicit operator Opportunity(Lead lead)
{
Opportunity opp = new Opportunity();
opp.Id = lead.Id.ToString();
opp.FirstName = lead.FirstName;
opp.LastName = lead.LastName;
return opp;
}
}
void Main()
{
Lead lead = new Lead();
lead.Id = Guid.NewGuid();
lead.FirstName = "Vinod";
lead.LastName = "Srivastv";
lead.Dump();
Opportunity opp = (Opportunity)lead;
opp.Dump();
}
当我们更改关键字时,编译器会抛出错误,错误信息为“存在显式转换(是否缺少强制转换?)”,因此我们需要将
Lead
对象转换为
Opportunity
对象,如上所示,使用
(Opportunity)
进行强制转换。
![enter image description here](https://istack.dev59.com/RNkLv.webp)