简体   繁体   English

我可以在C#中使用不同的类型初始化类的公共属性吗?

[英]Can I initialize public properties of a class using a different type in C#?

In Java, I can have an object like this: 在Java中,我可以有一个像这样的对象:

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

}

This is nice, because I have one getter for my properties, and multiple setters. 这很好,因为我的属性和多个setter有一个getter。 I can set the "date" property by passing in either a Date object, or a String, and let the class figure it out. 我可以通过传入Date对象或String来设置“date”属性,然后让类弄清楚它。

In C# it looks like things are a little different. 在C#中,看起来事情有点不同。 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. 但是,我不确定是否有任何内置方法可以重置setter以接受多种类型。 I realize I could create a separate public method to set the value, but that would sacrifice the ability to use object initializers. 我意识到我可以创建一个单独的公共方法来设置值,但这会牺牲使用对象初始化器的能力。

Is there any way to directly overload the setter on public properties for C#? 有没有办法直接重载C#公共属性的setter? 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. Use a second property with just a setter: 使用第二个属性只有一个setter:

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

    Avoid this if possible, it only adds confusion :-) 尽可能避免这种情况,只会增加混乱:-)

  2. Use methods instead of properties (same as you do in Java). 使用方法而不是属性(与在Java中一样)。 Methods can be overloaded. 方法可以重载。 This should be the most recommended way. 这应该是最推荐的方式。

  3. Use a custom class (instead of DateTime ) and provide implicit conversions between DateTime , string , and your class. 使用自定义类(而不是DateTime )并在DateTimestring和您的类之间提供隐式转换。 Not recommended unless you are going to use this everywhere else. 除非你打算在其他地方使用它,否则不推荐使用。

  4. Change the property to object and provide your conversions in the setter: please don't do this 将属性更改为object并在setter中提供转换:请不要这样做

Well, you're comparing apples to bananas. 嗯,你把苹果和香蕉比较。 What you have in Java here: 你在Java中有什么:

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

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

Would look like this in C#: 在C#中看起来像这样:

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

public void SetDate(String date) 
{
    this.date = ParseDateString(date);
}

The only difference being the PascalCase member names and the location of the scope-opening brace. 唯一的区别是PascalCase成员名称和范围开放括号的位置。

Your Java code has overloaded methods ; 您的Java代码有重载方法 ; the above C# has overloaded methods. 上面的C#有重载方法。

AFAIK you can't overload a property setter, because: AFAIK你不能重载属性setter,因为:

public DateTime Date 
{ 
    get { return this.date; }
    set { this.date = value; }
}

...the type of value is determined by the type of the member, here DateTime . ... value的类型由成员的类型决定,这里是DateTime

So if you want method overloads, overload methods , not properties . 所以如果你想要方法重载,重载方法 ,而不是属性 Remember that C# properties are just syntax sugar for getter & setter methods anyway. 请记住,无论如何,C#属性只是getter和setter方法的语法糖。

The auto properties do not support this. 自动属性不支持此功能。 So you will have to do the same as you do in Java. 所以你必须像在Java中那样做。

Of course you could mix these as well: provide an auto property and extra set-methods to set the property using different types. 当然你也可以混合这些:提供一个自动属性和额外的set方法来使用不同的类型设置属性。

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

    public void SetDate(string date) 
    {
        this.Date = DateTime.Parse(date);
    }    
}

I'm going to write a different answer and claim that 我将写一个不同的答案并声称

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

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

is bad practice to begin with. 开始时是不好的做法。

By doing the above, you are claiming that both strings and dates are valid values for Date . 通过执行上述操作,您声称字符串和日期都是Date有效值。 This is not the case - what you really want is a Date . 事实并非如此 - 你真正想要的是一个Date If the user has a string and wants it converted a Date , they should be relying on the string-parsing functionality in the Date API ( DateFormat.parse() in Java, DateTime.Parse() in C#) , not your API. 如果用户有一个字符串并希望它转换为Date ,那么它们应该依赖于Date API中的字符串解析功能DateFormat.parse() Java中的DateFormat.parse() DateTime.Parse() ,C#中的DateTime.Parse() ,而不是您的API。

If Date is a class defined by you and you really do want Date and string to be interchangable, you should be using implicit conversations in the Date class, not asking users of your Date class to write overloads. 如果Date是您定义的类,并且您确实希望Datestring可以互换,那么您应该在Date类中使用隐式对话 ,而不是要求Date类的用户写入重载。

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

相关问题 C#泛型类,如何使用类型参数的派生类的公共属性? - C# Generic Class, how can I use public properties of derived class of type parameter? 在其他公共类中初始化变量时发生C#错误 - C# Error when initialize a variable in a different public class 如何在C#for循环中初始化多个不同类型的变量? - How can I initialize multiple variables of different type in a C# for loop? 如果我向C#类添加一个公共方法,我是否需要使用该类型重新编译其他程序集? - If I add a public method to a C# class, do I need to recompile other assemblies using that type? 在C#中,如何使用不同程序集中的公共类成员(方法或变量) - In C#, How Can I Use Public Class Members(Methods Or Variables) From Different Assembly C#-无法访问其他类的公共功能 - C# - Can't access public function from different class 我可以在C#*中使用*块使用不同类型的对象吗? - Can i have different type of objects in a C# *using* block? 在 C# 中创建每次都可以具有不同属性的类或对象 - Create an class or an object that can have different properties everytime in C# 为什么我可以在C#中执行此操作?(带有()的公共类 - Why can i do this in C#?(public class with ()) 如果在C#中的字符串中有类型名称,如何获取对象的公共属性? - How do I get the public properties of an Object if I have the type name in a string in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM