2009-09-03 48 views
1

在C#3.0中,我正在执行下面的代码来声明一个DateTime属性和一个只读的int age属性。C#3.0如何获取只读属性值?

public class MyClass{ 
    public DateTime dateOfBirth{ get; set; } 
    public int age { get; } 

    public MyClass(){} 

    public int CalculateAge(){} 
} 

但如何我能得到这个更新的时代(这是只读)当有人进入他的出生日期的形式,例如?

+3

我甚至不知道有可能声明一个自动实现的属性而没有设置块(私有会很好),因为你永远无法初始化属性。 – 2009-09-03 19:39:58

+3

这是不可能的 - 编译器会抱怨,正是因为你给的原因。 – 2009-09-03 19:40:47

回答

7

不要存放岁,执行年龄属性获取时,而不是计算的话:

public int Age { get { return 100; } }

但不是返回100,你做计算。

+0

我试过这样做,但在我的CalculateAge方法中,它说Age不能被分配,因为它是只读的。 – AndreMiranda 2009-09-03 19:41:38

+4

他说'不要存储年龄...' – n8wrl 2009-09-03 19:45:02

+0

谢谢!它为我工作! – AndreMiranda 2009-09-03 19:51:07

0

把你的代码来计算年龄属性的年龄。

例如:

public int Age 
{ 
    get 
    { 
      return (age code here); 
    } 
} 
+0

不会编译。您不能将时间范围隐式转换为int。 – 2009-09-03 19:39:46

+0

是的,我发布后立即意识到这一点。 – mgbowen 2009-09-03 19:40:38

+0

@Reed Copsey - 在黑暗的代码中没有时间跨度;它只是在回报中说'年龄代码'。用于计算整数年龄值的实际代码进入不合格状态。 – JeremyDWill 2009-09-03 19:44:58

8

你需要实现“年龄”属性,因此它的工作原理断出生日期属性:

public int age { 
    get { 
     return (DateTime.Now - this.dateOfBirth).Days/365; 
    } 
} 
+0

我相信有更好的方法来确定年龄。闰年和所有... – 2009-09-03 20:27:02

+1

是的 - 嗯,我只是试图展示技术,而不是具体细节。 – 2009-09-03 20:28:46

2

不能使用自动只读属性这一点。你必须执行该属性。你也可以考虑使用TimeSpan而不是int,因为它会更通用。

public TimeSpan Age 
{ 
    get 
    { 
     return DateTime.Now - this.dateOfBirth; 
    } 
} 
0

为什么不改变你的实现一点:

public class MyClass 
{ 
    public DateTime DateOfBirth {get; set;} 
    public int Age 
    { 
     get 
     { 
      return this.CalculateAge(); 
     } 
    } 
} 
2

而不必Age是一个自动财产,实施的年龄计算器。

public class MyClass { 
    public DateTime DateOfBirth { get; set; } 
    public int Age { 
     get { 
      DateTime now = DateTime.Now; 
      int age = now.Year - DateOfBirth.Year; 
      if(now < DateOfBirth.AddYears(age)) age--; 
      return age; 
     } 
    } 
} 

您应该将上面的计算重构为一个方法,但上面说明了这一点。

1

如果你希望只有您可以分配一个属性,但任何人都可以阅读:

public class MyClass 
{ 
    public int Age { get; private set; } 
} 

然后你的类可以分配Age,但其他类只能读取它。