如何编写代码来获取类的所有属性

本文关键字:属性 获取 何编写 代码 | 更新日期: 2023-09-27 18:21:44

我有一个程序,我想根据值创建一个对象的新实例,我获取值,然后搜索列表,并使用该列表创建一个新实例。

嗯,一切都很顺利。但有一个问题,我必须手动编写它们,这需要很长时间。我想知道是否有更好的方法来做这件事,这是我有的C#代码

public Account (int userId) {
    // here is look for the account
    // inside a List<Account> which returns the account
    // then I update the values for that instance, 
    this.AccountLockedSince = account.AccountLockedSince;
    this.AuthenticationToken = account.AuthenticationToken;
    this.CreateDate = account.CreateDate;
    this.IsLocked = account.IsLocked;
    this.IsVerified = account.IsVerified;
    this.PasswordResetDate = account.PasswordResetDate;
    this.PasswordResetToken = account.PasswordResetToken;
    this.RequireEmailVerification = account.RequireEmailVerification;
    this.TokenExpires = account.TokenExpires;
    this.UserId = account.UserId;
}

正如你所看到的,这些都是Account类的所有属性,我已经更新了它们,但这不是有效的方法。C#框架中有任何内置功能可以处理此问题吗?

如何编写代码来获取类的所有属性

尝试MemberwiseClone。

MemberwiseClone方法通过创建一个新对象,然后将当前对象的非静态字段复制到新对象来创建浅层副本。如果字段是值类型,则执行该字段的逐位复制。如果字段是引用类型,则复制引用,但不复制引用的对象;因此,原始对象及其克隆引用的是同一个对象。

如果您需要深层副本,而不是浅层副本,请尝试使用序列化来创建深层副本。

也可以使用"反射"获取和设置属性。请参见使用反射进行深度复制。

MemberwiseClone很好,但我建议安装AutoMapper金块包并开始使用它!它真的很通用,我在工作中经常使用它。

这个想法是,如果你想复制一个对象的属性,你可以

    var shallowCopy = Mapper.DynamicMap<Account>(account);

The good thing is that you can define mappings between types beforehand, like this:

    Mapper.CreateMap<TypeA, TypeB>()
          .ForMember(b => b.Tutu, opt => opt.MapFrom(a => a.Toto.Titi));
This way, when you will map from a TypeA to a TypeB, the propery Tutu of TypeB will be filled by the property Titi of Toto in TypeA. These mappings have lots of options to handle all the cases you may wish to handle ;)

I see you want to automate updating of the properties of your class - for which the answers given above might be fine. But if you simply want to get the names of all the properties of the class the following is the simplest way, I guess.

 IEnumerable<string> properties = typeof(Account).GetProperties().Select(p => p.Name);