简体   繁体   English

C#中的自动类型转换

[英]Automatic type Conversion in C#

I know that you could override an object's ToString() Method, so that everytime you call an object or pass it to a function that requires a String type it will be converted to a String.我知道您可以覆盖对象的 ToString() 方法,这样每次调用对象或将其传递给需要 String 类型的函数时,它都会被转换为 String。

I have written several extension methods for object type 'object'我已经为对象类型“object”编写了几种扩展方法

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());
}

so that I could just call them like this:这样我就可以这样称呼它们:

eventObject.Cost = row["cost"].ToString();
eventObject.EventId = row["event_id"].ToLong();

However, what I want to accomplish is to convert the row objects which is of type 'object' to its correct type based on the property types on my 'eventObject'.但是,我想要完成的是根据我的“eventObject”上的属性类型将“object”类型的行对象转换为正确的类型。 So, I could call it like this:所以,我可以这样称呼它:

eventObject.Cost = row["cost"];
eventObject.EventId = row["event_id"];

The row is a DataRow if that matters.如果重要的话,该行是 DataRow。

C# supports implicit conversion for types and you can use it for your custom types like the following: 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 
     }
 }

And supports extension methods , but doesn't support implicit conversion as an extension method like the following:并且支持扩展方法,但支持隐式转换作为扩展方法,如下所示:

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

I know that you could override an object's ToString() Method, so that everytime you call an object or pass it to a function that requires a String type it will be converted to a String.我知道您可以覆盖对象的 ToString() 方法,这样每次调用对象或将其传递给需要 String 类型的函数时,它都会被转换为 String。

No, you are wrong.不,你错了。 The following code won't compile:以下代码无法编译:

class MyClass
{
    public override string ToString()
    {
        return "MyClass";
    }
}

static void MyMethod(string s) { }

static void Main(string[] args)
{
    MyMethod(new MyClass());   //compile error
}

The compiler will not get the type of MyMethod parameter(which is string ) first and try to convert the argument you passed(whose type is MyClass ) to it.编译器不会首先获取MyMethod参数的类型(即string )并尝试将您传递的参数(其类型为MyClass )转换为它。 I guess you are probably mislead by something like Console.WriteLine .我想你可能被Console.WriteLine类的东西误导了。 Base on the code above, Console.WriteLine(new MyClass()) prints "MyClass" to the console, it seems that the compiler knows you should pass a string to Console.WriteLine and try to convert MyClass to string.基于上面的代码, Console.WriteLine(new MyClass()) “MyClass”打印到控制台,似乎编译器知道您应该将字符串传递给Console.WriteLine并尝试将MyClass转换为字符串。 But the essential is Console.WriteLine has several overloads, one of them is for object :但重要的是Console.WriteLine有几个重载,其中之一是用于object

//from Console.cs
public static void WriteLine(object value)
{
    //in this method there is something like
    //Console.WriteLine(value.ToString());
}

I believe what you're looking for is implicit conversion, which is described here: http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx .我相信您正在寻找的是隐式转换,此处描述: http : //msdn.microsoft.com/en-us/library/z5z9kes2.aspx

However, adding these to object would be a very bad idea, for reasons outlined on the page I've linked to.但是,出于我链接到的页面上概述的原因,将这些添加到对象将是一个非常糟糕的主意。

To sum up - just define these methods and you can use objects of class Test in methods requiring String as a parameter.总而言之 - 只需定义这些方法,您就可以在需要 String 作为参数的方法中使用类 Test 的对象。

class Test
{
    private String txt;

    public static implicit operator string(Test t)
    {
        return t.ToString();
    }

    public override string ToString() 
    {
        return txt;
    }
}

Forgive me if I'm stating the obvious but I got this impression after reading your question.请原谅我,如果我说的是显而易见的,但在阅读您的问题后我得到了这种印象。

You know the basetype of every type in .NET is object right?你知道 .NET 中每种类型的基类型都是对象吗? So the column in the datarow which you describe of type object could also just as well be of the same type as the member you're trying to assign to and then a simple cast is needed.因此,您描述的数据行中类型为 object 的列也可以与您尝试分配给的成员具有相同的类型,然后需要一个简单的强制转换。

for instance例如

eventObject.EventId = (int)row["event_id"]; eventObject.EventId = (int)row["event_id"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM