如何一次分配给所有类数据成员 [英] How to assign to all class data members at once

查看:63
本文介绍了如何一次分配给所有类数据成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Dapper ORM 应用程序中,我想一次将一个对象分配给另一个或所有数据成员.像这样:

In a Dapper ORM application, I want to assign one object to another, or all data members at once. Like this:

public class TableA
{
    public int    UserId   { get; set; }
    public string ClientId { get; set; }
    // ... more fields ...

    public bool Query()
    {
        bool Ok = false;
        try{
            // Method A
            TableA Rec = QueryResultRecords.First(); 
            MyCopyRec(Rec, this);                        // ugly

            // Method B
            this = QueryResultRecords.First();           // avoids CopyRec, does not work

            Ok = true;
        }
        catch(Exception e){
            Ok = false;
        }
        return Ok;
    }
}

使用方法A,您可以将.First() 中的对象直接分配给class TableA 的新对象,并且需要自定义方法MyCopyRec获取同一个类的数据成员中的数据.

With Method A you can assign the object from .First() directly to a new object of class TableA, and need a custom method MyCopyRec to get the data in the data members of the same class.

但是,使用方法 B,您不能将相同的对象直接分配给 this.

However, with Method B you cannot assign the same object directly to this.

或者有其他方法可以做到这一点吗?

Or is there another way to do this?

推荐答案

如果this"是引用类型,则不能将对象分配给this",例如一类.this"是指向当前类实例的指针.这仅在这是一个值类型时才有效,例如一个结构体.

You cannot assign a object to "this" if "this" is a reference type, e.g. a class. "this" is a pointer to the current class instance. This would only work if this is a value type, e.g. a struct.

您只能为this"的属性赋值(这可能在 (CopyRec 方法) 中发生,例如:

You can only assign values to properties of "this" (which is what probably happens in the (CopyRec method), like:

var result = QueryResultRecords.First();
this.UserId  = result.UserId;

这篇关于如何一次分配给所有类数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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