C#中的自动类型转换

Aiv*_*ler 14 .net c# overriding casting type-conversion

我知道您可以覆盖对象的ToString()方法,这样每次调用对象或将其传递给需要String类型的函数时,它都将转换为String.

我已经为对象类型'对象'编写了几种扩展方法

public static DateTime ToDate(this object date)
{
    return DateTime.Parse(date.ToString());
}

public static int ToInteger(this object num)
{
    return Int32.Parse(num.ToString());
}

public static long ToLong(this object num)
{
    return Int64.Parse(num.ToString());
}
Run Code Online (Sandbox Code Playgroud)

所以我可以像这样打电话给他们:

eventObject.Cost = row["cost"].ToString();
eventObject.EventId = row["event_id"].ToLong();
Run Code Online (Sandbox Code Playgroud)

但是,我想要实现的是根据我的'eventObject'上的属性类型将'object'类型的行对象转换为正确的类型.所以,我可以这样称呼它:

eventObject.Cost = row["cost"];
eventObject.EventId = row["event_id"];
Run Code Online (Sandbox Code Playgroud)

如果重要的话,该行是DataRow.

Hom*_*mam 32

C#支持类型的隐式转换,您可以将它用于自定义类型,如下所示:

 class CustomValue
 {
     public static implicit operator int(CustomValue v)  {  return 4;  }

     public static implicit operator float(CustomValue v) {  return 4.6f;  }
 }

 class Program
 {
     static void Main(string[] args)
     {
         int x = new CustomValue(); // implicit conversion 
         float xx = new CustomValue(); // implicit conversion 
     }
 }
Run Code Online (Sandbox Code Playgroud)

并支持扩展方法,但支持隐式转换作为扩展方法,如下所示:

static class MyExtension
{
    // Not supported
    public static implicit operator bool(this CustomValue v)
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)