我只是想知道C#的value访问器中的set变量的数据类型是什么?
因为我想在C#的set访问器中实现类型提示。
例如,我有一个setter方法:
public User
{
private string username;
public void setUsername(SingleWord username)
{
this.username = username.getValue(); // getValue() method from "SingleWord" class returns "string"
}
}现在,我如何在C#的访问器语法中实现这一点?
public User
{
public string Username
{
get ;
set {
// How do I implement type-hinting here for class "SingleWord"?
// Is it supposed to be:
// this.Username = ((SingleWord)value).getValue(); ???
}
}
}这样我就可以这样称呼它:
User newuser = new User() {
Username = new SingleWord("sam023")
};提前感谢!
编辑:这是SingleWord的源代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Guitar32.Exceptions;
using Guitar32.Common;
namespace Guitar32.Validations
{
public class SingleWord : Validator, IStringDatatype
{
public static String expression = "^[\\w\\S]+$";
public static String message = "Spaces are not allowed";
private String value;
public SingleWord(String value, bool throwException = false) {
this.value = value;
if (throwException && value != null) {
if (!this.isValid()) {
throw new InvalidSingleWordException();
}
//if (this.getValue().Length > 0) {
// if (!this.isWithinRange()) {
// throw new Guitar32.Exceptions.OutOfRangeLengthException();
// }
//}
}
}
public int getMaxLength() {
return 99999;
}
public int getMinLength() {
return 1;
}
public String getValue() {
return this.value;
}
public bool isWithinRange() {
return this.getValue().Length >= this.getMinLength() && this.getValue().Length <= this.getMaxLength();
}
public override bool isValid() {
return this.getValue().Length > 0 ? Regex.IsMatch(this.getValue(), expression) : true;
}
}
public class InvalidSingleWordException : Exception {
public InvalidSingleWordException() : base("Value didn't comply to Single Word format")
{ }
}
}我使用这个类提供后端验证,方法是将SingleWord添加为setter所需的数据类型。
发布于 2015-06-22 03:59:02
无论发生什么,value类型都是属性的类型。
所以在你的例子中,
public string Username
{
...
set
{
value.GetType() // -> string
...
}
}您所要寻找的简单解决方案就是在您的.getValue()实例上调用SingleWord,
User newuser = new User()
{
Username = new SingleWord("sam023").getValue()
};或者更好,但我想这是因为你没给我们看的代码,
User newuser = new User()
{
Username = "sam023"
};但如果这是绝对禁止的话,听起来你要找的是隐算子 on SingleWord。如果您有能力修改类,您可以添加一个类似于此的操作符,它将自动执行对string的转换,以便您应该能够使用所列出的语法。
public static implicit operator string(SingleWord d)
{
return d.getValue();
}https://stackoverflow.com/questions/30971896
复制相似问题