我只是想知道什麼是value
變量的C#的set
訪問的數據類型?C# - 「set」訪問器中「value」的數據類型是什麼?
因爲我想實現的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
源代碼:我用這個類通過添加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")
{ }
}
}
。
你可以嘗試像顯式類型轉換爲這裏找到: https://msdn.microsoft.com/en-us/library/85w54y0a.aspx –
值是關鍵字,其設置變量的預測值通過屬性到相同類型的指定值 –
@BabuJames感謝您的顯式類型轉換的想法。 –