具有不同设置和获取类型的访问器?

时间:2021-08-06 16:12:44

Simple question, hopefully a simple answer:

简单的问题,希望是一个简单的答案:

I'd like to do the following:

我想做以下事情:

private DateTime m_internalDateTime;
public var DateTimeProperty
{
   get { return m_internalDateTime.ToString(); } // Return a string
   set { m_internalDateTime = value; } // here value is of type DateTime
}

The above is just an example of what I'm trying to do. I'd like to have a public accessor to an internal variable of type x. I want the get that variable as a string, but set it using something of type x.

以上只是我想要做的一个例子。我想要一个x类型的内部变量的公共访问器。我希望将该变量作为字符串获取,但使用x类型设置它。

Is this possible?

这可能吗?

--edit--

I just realized I could do something like:

我才意识到我可以这样做:

private DateTime m_internalDateTime;
public object DateTimeProperty
{
   get { return m_internalDateTime.ToString(); } // Return a string
   set { m_internalDateTime = (DateTime)value; } // here value is of type DateTime
}

But then, let say I use type y instead of a "string" as my 'get' type. If I want to use "DateTimeProperty" else where in my code, I'd have to cast it.

但是,假设我使用类型y而不是“字符串”作为我的“获取”类型。如果我想在我的代码中使用“DateTimeProperty”,我必须抛出它。

6 个解决方案

#1


No. You can obviously add the .ToString() in the calling code, but you can't do what you propose without different names like this:

不。显然,您可以在调用代码中添加.ToString(),但如果没有不同的名称,则无法执行您的建议:

private DateTime m_internalDateTime;
public DateTime SetDateTime { set { m_internalDateTime = value; } }
public string GetDateTime   { get { return m_internalDateTime.ToString(); } } 

Or, even better to use methods instead of properties (as noted in the comments):

或者,甚至更好地使用方法而不是属性(如评论中所述):

private DateTime m_internalDateTime;
public void SetDateTime(DateTime dateTime) { m_internalDateTime = dateTime; }
public string GetDateTime() { return m_internalDateTime.ToString(); }

Keep in mind that var is for implicitly, compile-time typed variables, not dynamic variables.

请记住,var是隐式编译时类型变量,而不是动态变量。

Definitely do not do what you noted in your edit. It introduced a break in convention, possible performance implications (albeit slight), and significant localization problems.

绝对不要做你在编辑中记下的内容。它引入了约定的中断,可能的性能影响(尽管是轻微的),以及显着的本地化问题。

#2


As a property, no this is not possible. You could make Get and Set methods that are of different types, but for a property the types must be the same.

作为一个财产,这是不可能的。您可以创建不同类型的Get和Set方法,但对于属性,类型必须相同。

EDIT:

While:

private DateTime m_internalDateTime;
public object DateTimeProperty
{
   get { return m_internalDateTime.ToString(); } // Return a string
   set { m_internalDateTime = (DateTime)value; } // here value is of type DateTime
}

is syntactically correct, will compile and allows you to accept DateTime as input and return a string, this would not be a good plan. It works, but it makes you and anyone accessing this code, perform unneeded validation. Additionally, it is vulnerable to another developer in the future, not knowing, or realizing the implicit rules, for which you have lost compile time safety. Additionally, its hardly any more code to create either two properties, or two methods that accomplish the same goal, in a strongly typed manner.

在语法上是正确的,将编译并允许您接受DateTime作为输入并返回一个字符串,这不是一个好的计划。它有效,但它使您和任何人访问此代码,执行不需要的验证。此外,它在将来容易受到其他开发人员的攻击,不知道或者意识到隐藏的规则,因为您已经失去了编译时的安全性。此外,它几乎不再需要以强类型方式创建两个属性或两个实现相同目标的方法。

Personally, I would recommend using two methods (see Jeff Yates comment for a good explanation as to why).

就个人而言,我建议使用两种方法(请参阅Jeff Yates的评论以获得有关原因的详细解释)。

private DateTime m_internalDateTime;
public string GetDateTime()
{
    return m_internalDateTime.ToString();
}

public void SetDateTime(DateTime dateTime)
{
    m_internalDateTime = dateTime;
}

#3


Not that way, but you can certainly have a second property that accesses the m_internalDateTime field.

不是这样,但你肯定有第二个属性访问m_internalDateTime字段。

public string DateTimeString
{
   get { return m_internalDateTime.ToString(); }
}

#4


Maybe that helps

也许这有帮助

public class TDecimal
{
    private decimal? m_value;
    public bool HasValue { get { return m_value.HasValue; } }
    public decimal Value { get { return m_value.Value; } }

    public static implicit operator TDecimal(string a_value)
    {
        decimal d;
        if (decimal.TryParse(a_value, out d))
        {
            return new TDecimal() {m_value = d};
        }

        return new TDecimal() {m_value = null};
    }

    public static implicit operator decimal(TDecimal a_value)
    {
        if(a_value.HasValue)
        {
            return a_value.Value;
        }

        throw new ArgumentNullException("a_value");
    }
}

public class A
{
    public TDecimal Prop { get; set; }
}


A a = new A();

a.Prop = "123";
if (a.Prop.HasValue)
{
    decimal d = a.Prop;
}

#5


Simple answer no, to your outside code your property will behave the exact way that a field would, you can't have a property having different set/get types just as you couldn't have a filed be set with a type and when you request it's value get a different type back.

简单的回答不,对于你的外部代码你的属性将按照字段的确切方式运行,你不能拥有具有不同的set / get类型的属性,就像你没有一个字段设置类型和当你请求它的价值获得不同的类型。

#6


how about:

private DateTime intDT;
public string DateTimeProperty
{   
      get { return intDT.ToString(); } // Return a string   
      set 
      { 
         DateTime dt;
         if (DateTime.TryParse(value, out dt))
             intDT = dt;
         else throw new ArgumentException(string.Format(
           "{0} cannot be converted to a DateTime.", value);           
      } 
}

#1


No. You can obviously add the .ToString() in the calling code, but you can't do what you propose without different names like this:

不。显然,您可以在调用代码中添加.ToString(),但如果没有不同的名称,则无法执行您的建议:

private DateTime m_internalDateTime;
public DateTime SetDateTime { set { m_internalDateTime = value; } }
public string GetDateTime   { get { return m_internalDateTime.ToString(); } } 

Or, even better to use methods instead of properties (as noted in the comments):

或者,甚至更好地使用方法而不是属性(如评论中所述):

private DateTime m_internalDateTime;
public void SetDateTime(DateTime dateTime) { m_internalDateTime = dateTime; }
public string GetDateTime() { return m_internalDateTime.ToString(); }

Keep in mind that var is for implicitly, compile-time typed variables, not dynamic variables.

请记住,var是隐式编译时类型变量,而不是动态变量。

Definitely do not do what you noted in your edit. It introduced a break in convention, possible performance implications (albeit slight), and significant localization problems.

绝对不要做你在编辑中记下的内容。它引入了约定的中断,可能的性能影响(尽管是轻微的),以及显着的本地化问题。

#2


As a property, no this is not possible. You could make Get and Set methods that are of different types, but for a property the types must be the same.

作为一个财产,这是不可能的。您可以创建不同类型的Get和Set方法,但对于属性,类型必须相同。

EDIT:

While:

private DateTime m_internalDateTime;
public object DateTimeProperty
{
   get { return m_internalDateTime.ToString(); } // Return a string
   set { m_internalDateTime = (DateTime)value; } // here value is of type DateTime
}

is syntactically correct, will compile and allows you to accept DateTime as input and return a string, this would not be a good plan. It works, but it makes you and anyone accessing this code, perform unneeded validation. Additionally, it is vulnerable to another developer in the future, not knowing, or realizing the implicit rules, for which you have lost compile time safety. Additionally, its hardly any more code to create either two properties, or two methods that accomplish the same goal, in a strongly typed manner.

在语法上是正确的,将编译并允许您接受DateTime作为输入并返回一个字符串,这不是一个好的计划。它有效,但它使您和任何人访问此代码,执行不需要的验证。此外,它在将来容易受到其他开发人员的攻击,不知道或者意识到隐藏的规则,因为您已经失去了编译时的安全性。此外,它几乎不再需要以强类型方式创建两个属性或两个实现相同目标的方法。

Personally, I would recommend using two methods (see Jeff Yates comment for a good explanation as to why).

就个人而言,我建议使用两种方法(请参阅Jeff Yates的评论以获得有关原因的详细解释)。

private DateTime m_internalDateTime;
public string GetDateTime()
{
    return m_internalDateTime.ToString();
}

public void SetDateTime(DateTime dateTime)
{
    m_internalDateTime = dateTime;
}

#3


Not that way, but you can certainly have a second property that accesses the m_internalDateTime field.

不是这样,但你肯定有第二个属性访问m_internalDateTime字段。

public string DateTimeString
{
   get { return m_internalDateTime.ToString(); }
}

#4


Maybe that helps

也许这有帮助

public class TDecimal
{
    private decimal? m_value;
    public bool HasValue { get { return m_value.HasValue; } }
    public decimal Value { get { return m_value.Value; } }

    public static implicit operator TDecimal(string a_value)
    {
        decimal d;
        if (decimal.TryParse(a_value, out d))
        {
            return new TDecimal() {m_value = d};
        }

        return new TDecimal() {m_value = null};
    }

    public static implicit operator decimal(TDecimal a_value)
    {
        if(a_value.HasValue)
        {
            return a_value.Value;
        }

        throw new ArgumentNullException("a_value");
    }
}

public class A
{
    public TDecimal Prop { get; set; }
}


A a = new A();

a.Prop = "123";
if (a.Prop.HasValue)
{
    decimal d = a.Prop;
}

#5


Simple answer no, to your outside code your property will behave the exact way that a field would, you can't have a property having different set/get types just as you couldn't have a filed be set with a type and when you request it's value get a different type back.

简单的回答不,对于你的外部代码你的属性将按照字段的确切方式运行,你不能拥有具有不同的set / get类型的属性,就像你没有一个字段设置类型和当你请求它的价值获得不同的类型。

#6


how about:

private DateTime intDT;
public string DateTimeProperty
{   
      get { return intDT.ToString(); } // Return a string   
      set 
      { 
         DateTime dt;
         if (DateTime.TryParse(value, out dt))
             intDT = dt;
         else throw new ArgumentException(string.Format(
           "{0} cannot be converted to a DateTime.", value);           
      } 
}