gpt4 book ai didi

c# - "value"访问器中 "set"的数据类型是什么?

转载 作者:行者123 更新时间:2023-11-30 14:52:46 25 4
gpt4 key购买 nike

我只是想知道 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的源代码:

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 所需的数据类型来提供后端验证。

最佳答案

无论如何,value 的类型就是属性的类型。

所以在你的例子中,

public string Username
{
...
set
{
value.GetType() // -> string
...
}
}

您正在寻找的简单解决方案是在您的 SingleWord 实例上调用 .getValue()

User newuser = new User()
{
Username = new SingleWord("sam023").getValue()
};

或者更好,但我认为这不会起作用,因为您没有向我们展示代码,

User newuser = new User()
{
Username = "sam023"
};

但如果那绝对不行,那么听起来您正在寻找的是 implicit operatorSingleWord 上。如果你有能力修改这个类,你可以添加一个看起来像这样的运算符,它会自动执行到 string 的转换,这样你就可以使用你的语法已经列出。

public static implicit operator string(SingleWord d)
{
return d.getValue();
}

关于c# - "value"访问器中 "set"的数据类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30971896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com