[C#]财产的属性? [英] [C#] property of property ?

查看:104
本文介绍了[C#]财产的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。有人可以解释我的属性.Now of DateTime有没有其他属性?例如:DateTime.Now.Year

我想做同样的事情:通过另一个访问该属性。



谢谢!



我的尝试:



在Google中搜索,现在在CodeProject.com中搜索

解决方案

属性现在返回对数据的引用宾语。这可以作为对象访问。



你只需要在属性getter中返回该类型的对象。



C#中的getter和setter 的一些解释和更复杂的示例。


这只是因为该属性返回一个对象,所以你可以然后访问它返回的对象的属性。



公共类数据
{
public int ID {get;组; }
public string Name {get;组; }
}

公共类MyClass
{
公共数据数据{get;组; }

public MyClass()
{
this.Data = new Data();
}
}





 MyClass c = new MyClass(); 
c.Data.ID = 1;





在上面,Data属性是对象的属性,如果你使它静态然后它是该类型的属性,并模拟DateTime.Now更好



公共类MyClass 
{
public static Data Data
{
get
{
return new Data();
}
}
}





 MyClass.Data.ID = 1; 


喜欢这个

公共类MyDateTime {
public static MyDateTime My_Now {get ; }
public int My_Year {get; }
}

 int year = MyDateTime.My_Now.My_Year; 



通过这些链接

C#中面向对象编程概念的介绍 [ ^ ]

属性 - {get;组; } - Stack Overflow [ ^ ]

使用属性(C#编程指南)| Microsoft Docs [ ^ ]

static(C#Reference)| Microsoft Docs [ ^ ]


Hi. Can someone explain me how the property .Now of DateTime has another properties in it ? For example: DateTime.Now.Year
I want to make the same thing: Accessing the property through the another one.

Thanks!

What I have tried:

Searching in Google and now asking here in CodeProject.com

解决方案

The property Now is returning the reference to an data object. That can be accessed as objects to.

You only must return an object of that type in the property getter.

Some explanation and more complex examples to getters and setters in C#.


It's simply because the property returns an object so you can then access the properties of the object it returns.

public class Data
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class MyClass
{
    public Data Data { get; set; }

    public MyClass()
    {
        this.Data = new Data();
    }
}



MyClass c = new MyClass();
c.Data.ID = 1;



In the above the Data property is a property of the object, if you make it static then it is a property of the type and that emulates DateTime.Now better

public class MyClass
{
    public static Data Data
    {
        get
        {
            return new Data();
        }
    }
}



MyClass.Data.ID = 1;


like this

public class MyDateTime {
       public static MyDateTime My_Now { get;  }
       public int My_Year { get; }
   }

int year = MyDateTime.My_Now.My_Year;


go through these links
Introduction to Object Oriented Programming Concepts in C#[^]
properties - { get; set; } - Stack Overflow[^]
Using Properties (C# Programming Guide) | Microsoft Docs[^]
static (C# Reference) | Microsoft Docs[^]


这篇关于[C#]财产的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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