C# 中的自动类型转换

发布于 2024-10-14 04:51:20 字数 757 浏览 2 评论 0原文

我知道您可以重写对象的 ToString() 方法,以便每次调用对象或将其传递给需要 String 类型的函数时,它都会转换为 String。

我已经为对象类型“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());
}

以便我可以像这样调用它们:

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

但是,我想要完成的是将“object”类型的行对象根据属性转换为正确的类型在我的“eventObject”上键入。因此,我可以这样称呼它:

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

如果重要的话,该行是一个 DataRow。

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.

I have written several extension methods for object type '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'. So, I could call it like this:

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

The row is a DataRow if that matters.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

许一世地老天荒 2024-10-21 04:51:20

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 
     }
 }

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

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

C# supports implicit conversion for types and you can use it for your custom types like the following:

 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;
    }
}
可是我不能没有你 2024-10-21 04:51:20

我知道你可以覆盖
对象的 ToString() 方法,这样
每次你调用一个对象或传递
它需要一个函数
它将被转换为字符串类型
字符串。

不,你错了。以下代码将无法编译:

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

static void MyMethod(string s) { }

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

编译器不会先获取 MyMethod 参数的类型(即 string),然后尝试转换您传递的参数(其类型为MyClass) 到它。我想您可能会被 Console.WriteLine 之类的东西误导。基于上面的代码,
Console.WriteLine(new MyClass())
将“MyClass”打印到控制台,编译器似乎知道您应该将字符串传递给Console.WriteLine 并尝试将 MyClass 转换为字符串。但最重要的是 Console.WriteLine 有几个重载,其中之一是针对 object 的:

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

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.

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. I guess you are probably mislead by something like 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. But the essential is Console.WriteLine has several overloads, one of them is for object:

//from Console.cs
public static void WriteLine(object value)
{
    //in this method there is something like
    //Console.WriteLine(value.ToString());
}
浮萍、无处依 2024-10-21 04:51:20

我相信您正在寻找的是隐式转换,如下所述: http: //msdn.microsoft.com/en-us/library/z5z9kes2.aspx

但是,由于我链接到的页面上概述的原因,将这些添加到对象将是一个非常糟糕的主意。

I believe what you're looking for is implicit conversion, which is described here: 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.

朮生 2024-10-21 04:51:20

如果我说的是显而易见的事情,请原谅我,但我在读完你的问题后得到了这个印象。

您知道 .NET 中每种类型的基本类型都是对象吗?
因此,您描述的类型对象的数据行中的列也可以与您尝试分配给的成员具有相同的类型,然后需要进行简单的转换。

例如

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

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?
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.

for instance

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

土豪我们做朋友吧 2024-10-21 04:51:20

总结一下 - 只需定义这些方法,您就可以在需要 String 作为参数的方法中使用 Test 类的对象。

class Test
{
    private String txt;

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

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

To sum up - just define these methods and you can use objects of class Test in methods requiring String as a parameter.

class Test
{
    private String txt;

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

    public override string ToString() 
    {
        return txt;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文