是否可以使用其他变量类型设置类变量 [英] Is it possible to set a class variable using a different variable type

查看:51
本文介绍了是否可以使用其他变量类型设置类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以为c#变量设置与变量类型设置不同的变量类型值?

is it possible to set a c# variable with a different variable type value than what the variable one is setting?

public class Test{

   public DateTime TimeSinceEpoch {
      get {return TimeSinceEpoch; }
      set{ 
         DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
         TimeSinceEpoch = Epoch.AddMilliseconds(value);}} //<-the value that's expected is a DateTime value..
}

我该怎么写:'TimeSinceEpoch = 1549090800000'并将TimeSinceEpoch用作普通的DateTime变量?

How can i write: 'TimeSinceEpoch = 1549090800000' and use TimeSinceEpoch as a normal DateTime variable?

无需在类内单独获取和设置变量

推荐答案

即使在 具有语法的C ++/CLI中,也不允许这样做:

This isn't allowed even in C++/CLI which does have a syntax for it:

public ref struct Test
{
    property System::DateTime TimeSinceEpoch
    {
        DateTime get();
        void set(DateTime);
        void set(long long);
    }
};

您收到以下错误:

错误C3902:'设置':最后一个参数的类型必须为'System :: DateTime'

error C3902: 'set': type of last parameter must be 'System::DateTime'

Intellisense实际上会产生两个投诉,具体取决于您编写投诉的顺序:

Intellisense actually produces two complaints, depending on which order you write them:

E1930:已经在此属性中为此属性声明了设置"访问器

E1930: a 'set' accessor was already declared for this property at

E1942:设置"访问器的最后一个参数与属性类型不匹配

E1942: the last parameter of the 'set' accessor does not match the property type

潜在的问题是.NET属性必须在元数据中列出类型和最多一个setter(请查看

The underlying problem is that a .NET property has to list a type and a maximum of one setter in the metadata (Have a look at PropertyInfo.GetSetMethod -- it returns one setter or null, not an array). Even though you could easily overload the setter function itself:

void set_TimeSinceEpoch(DateTime)
void set_TimeSinceEpoch(long)

这两个功能中只有一个可以与该属性相关联.

only one of these two functions could be associated to the property.

您可以使用助手类型来允许多种传入类型:

You could use a helper type to allow multiple incoming types:

struct SuperDateTime
{
    public DateTime Value;
    public static implicit operator SuperDateTime(DateTime d) { return new SuperDateTime { Value = d }; }
    public static implicit operator SuperDateTime(long x) { return new SuperDateTime { Value = Epoch.AddMilliseconds(x) }; }
    public static implicit operator DateTime(SuperDateTime d) { return d.Value; }
}

但这会破坏该属性的读者,他们现在必须在使用成员之前说 TimeSinceEpoch.Value (如果将其作为参数传递给另一个函数,则隐式转换将开始).为了克服这个问题,您需要为 DateTime 的每个成员编写转发功能.

but this will break readers of the property, who now have to say TimeSinceEpoch.Value before using a member (if passing as an argument to another function, the implicit conversion will kick in). To overcome that, you'd need to write a forwarding function for every single member DateTime has.

这篇关于是否可以使用其他变量类型设置类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆