C# 属性可以接受多个值吗?
这可能有点反模式,但 C# 类上的属性可以接受多个值吗?
例如,假设我有一个 Public int 属性,并且我总是希望它返回一个 int,但我希望能够通过分配小数、整数或其他数据类型来设置该属性。 所以我的问题是属性是否可以接受多个值?
This might be a bit of an anti-pattern, but it is possible for a property on a C# class to accept multiple values?
For example, say I have an Public int property and I always want it to return an int, but I would like to be able to have the property set by assigning a decimal, an integer or some other data type. So my question is if it possible for properties to accept multiple values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我想你想问的是:如何隐式以及 显式
int
和 < code>decimal?您询问的是隐式转换,它会自动将一个对象转换为另一种定义的类型。 您将无法对
int
和decimal
执行此操作,因为它们已在框架中定义,并且您无法缩小decimal 的范围
将其转换为int
。 但是,如果您使用它作为创建的实际对象的示例,则可以使用 上面的隐式链接,以了解有关其工作原理以及如何实现的更多信息。但是您始终可以使用convert方法将它们转换为正确的类型;
I think what you mean to ask is: How does implicit and explicit casting work for
int
anddecimal
?You are asking about implicit casting which automatically coverts one object to another defined type. You will not be able to do this for an
int
anddecimal
because they are already defined in the framework and you are not able to reduce the scope of thedecimal
by casting it to anint
. But if you were using that as an example for actual objects that you created you can use the implicit link above, to learn more about how this works and how to implement it.But you can always use the convert method to convert them to the right type;
编辑:无法使用此方法,因为操作专门绑定到属性。
我认为以您所描述的稳健性这是不可能的。 在这种情况下,您可能最好使用重载方法(多态性)。
这就是通常所说的 setter(或 mutator),您可以重载该方法以接受多种不同类型的参数。 如果您愿意,每个人都会有不同的表现。 我设置它们的方式可能在语法上不正确,但我相信这是您正在寻找的总体想法。
Edit: This method can't be used since the op is specifically bound to properties.
I do not believe this is possible with the robustness that you describe. In this case you would likely be better off using an overloaded method (polymorphism).
This is what is typically known as a setter (or mutator) and you can overload the method to accept multiple different types of parameters. Each will perform differently if you wish. The way I have them set up might not be syntactically correct but that is the general idea you're looking for I believe.
不。属性具有单一值。 您可以将任何可以分配给相同类型变量的东西分配给它。
No. A property has a single value. You can assign anything to it that could be assigned to a variable of the same type.
看来您必须在运行时确定类型。 您可以让该属性接受一个对象,确定类型并采取操作。 当然,您必须为您意想不到的事情抛出异常。 就像你说的,可能不是最好的,但有可能。 :)
It seems like you would have to ascertain the type at run-time. You could have the property accept an object, determine the type and take your action. You would have to throw exceptions for things you don't expect, of course. Like you say, probably not the best, but possible. :)
属性应该看起来有点像公共字段。 创建 setter 方法,或者在赋值语句中而不是在属性 setter 中进行转换/转换。
Properties are supposed to look sort of like public fields. Create setter-methods, or do the cast/conversion in the assignment statements as opposed to in the property-setter.