我可以初始化使用C#中的不同类型的类的公共属性? [英] Can I initialize public properties of a class using a different type in C#?

查看:111
本文介绍了我可以初始化使用C#中的不同类型的类的公共属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我能有这样一个对象:

In Java, I can have an object like this:

public class MyObject {

    private Date date;

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public void setDate(String date) {
        this.date = parseDateString(date);
    }

    private Date parseDateString(String date) {
        // do magic here
        return dateObj;
    }

}

这是很好的,因为我有一个获取方法对我的属性,多个setter方法。我可以通过传递在任何一个Date对象,或者一个字符串设定日期属性,并让班看着办吧。

This is nice, because I have one getter for my properties, and multiple setters. I can set the "date" property by passing in either a Date object, or a String, and let the class figure it out.

在C#中,它看起来像的东西有一点不同。我可以这样做:

In C# it looks like things are a little different. I can do this:

public class MyObject
{
    public DateTime Date { get; set; }
}

下面速记显然是最佳的。但是,我不知道是否有超载二传手接受多种类型的内置方式。我知道我可以创建一个单独的公共方法来设置值,但是会牺牲使用对象初始的能力。

The shorthand here is obviously optimal. However, I'm not sure if there's any built-in way to overload the setter to accept multiple types. I realize I could create a separate public method to set the value, but that would sacrifice the ability to use object initializers.

有没有办法直接超载二传手公共属性的C#?或者这只是一门语言的限制,并且不能做?

Is there any way to directly overload the setter on public properties for C#? Or is this just a language limitation, and it can't be done?

推荐答案

所有其他的答案是正确的......但如果你坚持,你可以做以下几种方式:

All other answers are correct... but if you insist, you can do it in several ways:


  1. 使用第二套房产只二传手:

  1. Use a second property with just a setter:

public string DateText { set { Date = ParseDateString(value); } }

如果有可能避免这种情况,只会增加混乱: - )

Avoid this if possible, it only adds confusion :-)

使用方法,而不是属性(一样的,你在Java中这样做)。方法可以被重载。这应该是最值得推荐的方法。

Use methods instead of properties (same as you do in Java). Methods can be overloaded. This should be the most recommended way.

使用自定义类(而不是的DateTime ),并提供的DateTime 字符串和类之间的隐式转换。不推荐,除非你要使用这个其他地方。

Use a custom class (instead of DateTime) and provide implicit conversions between DateTime, string, and your class. Not recommended unless you are going to use this everywhere else.

更改属性对象并提供您在二传手的转换:请不要这样做

Change the property to object and provide your conversions in the setter: please don't do this

这篇关于我可以初始化使用C#中的不同类型的类的公共属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆