C# 属性设置器中的多种输入类型

发布于 2024-11-25 06:46:47 字数 251 浏览 1 评论 0原文

我有一个如下所示的属性:

private int clientID;

    public int ClientID
    {
        get { return clientID; }
        set { clientID = value; }
    }

我希望能够将字符串传递给该属性,以便设置器为我转换它。我该怎么做?

我知道如何进行转换,我只需要知道如何传入字符串而不引发类型错误。

I have a property that looks like this:

private int clientID;

    public int ClientID
    {
        get { return clientID; }
        set { clientID = value; }
    }

I would like to be able to pass in a string to this property so that the setter will convert it for me. How do I do that?

I know how to do the conversion, I just need to know how to pass in a string without it throwing a type error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

睫毛溺水了 2024-12-02 06:46:47

基本上你不能。选项:

  • 将 ClientID 的第二个属性设置为文本(由同一字段支持)
  • 使用单独的方法(例如 SetClientID(string)
  • 将属性类型更改为 object 并根据传入的值做不同的事情(呃 - 请不要这样做!)

You can't, basically. Options:

  • Have a second property for the ClientID as text (backed by the same field)
  • Have a separate method (e.g. SetClientID(string))
  • Change the property type to object and do different things based on the value passed in (urgh - please don't do this!)
蓝色星空 2024-12-02 06:46:47

你不能。不过,您可以创建这样的方法

public void SetClientId(string clientId)
{
    this.ClientID = Convert.ToInt32(clientId);
}

You cannot. You can create a method like this though

public void SetClientId(string clientId)
{
    this.ClientID = Convert.ToInt32(clientId);
}
究竟谁懂我的在乎 2024-12-02 06:46:47

您不能将字符串传递给声明为整数的属性。您可以改用一种方法。

You can't pass a string to a property which is declared as integer. You could use a method instead.

深海不蓝 2024-12-02 06:46:47

我建议你不要尝试。你只会给以后的约会带来麻烦。

添加一个额外的 setter,

public string ClientIDText
{
    set
    {
        clientID = int.Parse(value);
    }
}

或者创建一个 SetClientID(string) 方法。

创建 SetClientID 方法有一个优点;您可以创建重载,因此您可以创建

SetClientID(int)
SetClientID(string)
etc.

但是,我仍然认为您为了方便保存几行代码而在应用程序中构建了歧义。

I recommend you don't try. You're only causing headaches for a later date.

Add an additional setter, instead...

public string ClientIDText
{
    set
    {
        clientID = int.Parse(value);
    }
}

or create a SetClientID(string) method.

There is an advantage to create a SetClientID method; you can create overloads, so you could create

SetClientID(int)
SetClientID(string)
etc.

However, I still think you're building ambiguity into your app for the convenience of saving a few lines of code.

地狱即天堂 2024-12-02 06:46:47

或者,您可以提供一个 ClientID 类,该类在自身、int 和 string 之间进行隐式转换,然后您可以拥有一个属性:

public ClientIdType ClientId
{
    get; set;
}

但所有调用者都可以这样使用它:

var myClass = new MyClass();
myClass.ClientId = 1;
myClass.ClientId = "2";

int id = myClass.ClientId;

http://msdn.microsoft.com/en-us/library/85w54y0a.aspx

但是,这似乎是大量的跑腿工作只是为了让呼叫者更容易,但这仍然是一个选择。

Alternatively, you can provide a ClientID class that has implicit conversion between itself, int and string, then you can have a property:

public ClientIdType ClientId
{
    get; set;
}

But all the callers could then use it thus:

var myClass = new MyClass();
myClass.ClientId = 1;
myClass.ClientId = "2";

int id = myClass.ClientId;

http://msdn.microsoft.com/en-us/library/85w54y0a.aspx

However, this seems like a lot of legwork just to make it easier for the caller, but it's still an option.

生生漫 2024-12-02 06:46:47

我认为最干净的解决方案是,正如其他人建议的那样,创建一个 ClientId 类。我认为这不一定是坏事,正如 这篇 文章中所解释的那样一个非常好的方法:

许多类都有消耗或公开原始值的倾向
就像整数和字符串一样。虽然此类原始类型存在于任何
平台,它们往往会导致程序代码。此外,他们经常
通过允许分配无效值来破坏封装。

如果需要的话,拥有一个单独的类也可以为您提供不同类型的验证 id 的可能性。最后,一切都与封装有关。

像这样的事情应该可以帮助您开始:

//auto-property for your class
public ClientId ClientID
{
   get; set;
}

还有 ClientId 类:

public class ClientId
{
  private int _id;

  public ClientId(int id) { _id = id; }
  public ClientId(string id) { //convert id to int, throw exception if invalid }

  public int Value { return _id; }
}

不要忘记实现 Equals 和 GetHashCode,对于此类来说这可以轻松完成。

I think the cleanest solution is, as some others have suggested is to create a ClientId class. I don't think this is necessarily bad, as this post explains in a pretty good way:

Many classes have a tendency to consume or expose primitive values
like integers and strings. While such primitive types exist on any
platform, they tend to lead to procedural code. Furthermore they often
break encapsulation by allowing invalid values to be assigned.

Having a seperate class gives you different sorts of possibilities to validate the the id as well, if that is a requirement. In the end, it is all about encapsulation.

Something like this should get you started:

//auto-property for your class
public ClientId ClientID
{
   get; set;
}

And the ClientId class:

public class ClientId
{
  private int _id;

  public ClientId(int id) { _id = id; }
  public ClientId(string id) { //convert id to int, throw exception if invalid }

  public int Value { return _id; }
}

Don't forget to implement Equals and GetHashCode as well, which can be done trivially for this class.

与往事干杯 2024-12-02 06:46:47

您不能重载属性,因此这是行不通的。

您可以做的就是

  1. 在设置之前将其转换为 int (首选)
  2. 创建一个方法来从客户端进行转换,即 SetClientIdFromString(strign id )

You can't overload properties, so that won't work.

What you can do is

  1. Just convert the thing to an int before setting it (preferred)
  2. Create a method to do the conversion from clients, i.e., SetClientIdFromString(strign id ).
丘比特射中我 2024-12-02 06:46:47

作为属性中的替代方案怎么样:

    private int rowValue_;
    public object RowValue
    {
        get
        {
            return this.rowValue_;
        }
        set
        {
            var type = value.GetType();
            if (type == typeof(string))
            {
                this.rowValue_ = Convert.ToInt32(value);
            }
            else if (type == typeof(int))
            {
                this.rowValue_ = (int)value;
            }
            else
            {
                throw new InvalidDataException(
                    "HandwritingData RowValue can only be string or int. 
                    Passed in parameter is typeof {0}",
                    value.GetType().ToString());
            }
        }
    }

它对我有用,并且可以捕获错误的参数。

问候,
克里斯

How about as an alternative in the property:

    private int rowValue_;
    public object RowValue
    {
        get
        {
            return this.rowValue_;
        }
        set
        {
            var type = value.GetType();
            if (type == typeof(string))
            {
                this.rowValue_ = Convert.ToInt32(value);
            }
            else if (type == typeof(int))
            {
                this.rowValue_ = (int)value;
            }
            else
            {
                throw new InvalidDataException(
                    "HandwritingData RowValue can only be string or int. 
                    Passed in parameter is typeof {0}",
                    value.GetType().ToString());
            }
        }
    }

It works for me as well as trapping bad parameters.

Regards,
Chris

﹂绝世的画 2024-12-02 06:46:47

在此示例中 如何继承 string 类? 有一个如果您可以忍受拥有一个不是纯字符串的属性,但可以作为一个属性并且能够 投掷:

class Foo {
    readonly string _value;
    public Foo(string value) {
        this._value = value;
    }
    public static implicit operator string(Foo d) {
        return d.ToString();
    }
    public static implicit operator Foo(string d) {
        return new Foo(d);
    }
}

In this example How Can I inherit the string class? there is a nice contribution by René if you can stand having a property not being a pure string - but serve as one and be able to cast:

class Foo {
    readonly string _value;
    public Foo(string value) {
        this._value = value;
    }
    public static implicit operator string(Foo d) {
        return d.ToString();
    }
    public static implicit operator Foo(string d) {
        return new Foo(d);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文