我想知道在C#的set
访问器中,value
变量的数据类型是什么?
因为我想在C#的set访问器中实现类型提示。
例如,我有一个设置器方法:
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")
{ }
}
}
我使用了这个类来提供后端验证,通过在setter中添加SingleWord
作为所需的数据类型。