如何一次分配给所有类数据成员

时间:2015-10-28 13:38:31

标签: c# object

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

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来获取同一数据成员中的数据类。

但是,使用方法B,您无法将同一对象直接分配给this

或者还有另一种方法吗?

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

/// <summary>
/// Extension for 'Object' that copies the properties to a destination object.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="destination">The destination.</param>
public static void CopyProperties(this object source, object destination)
{
    // If any this null throw an exception
    if (source == null || destination == null)
        throw new ArgumentException("Source or/and Destination Objects are null");
    // Getting the Types of the objects
    Type typeDest = destination.GetType();
    Type typeSrc = source.GetType();

    // Iterate the Properties of the source instance and  
    // populate them from their desination counterparts  
    PropertyInfo[] srcProps = typeSrc.GetProperties();
    foreach (PropertyInfo srcProp in srcProps)
    {
        if (!srcProp.CanRead)
        {
            continue;
        }
        PropertyInfo targetProperty = typeDest.GetProperty(srcProp.Name);
        if (targetProperty == null)
        {
            continue;
        }
        if (!targetProperty.CanWrite)
        {
            continue;
        }
        if ((targetProperty.GetSetMethod().Attributes & MethodAttributes.Static) != 0)
        {
            continue;
        }
        if (!targetProperty.PropertyType.IsAssignableFrom(srcProp.PropertyType))
        {
            continue;
        }
        // Passed all tests, lets set the value
        targetProperty.SetValue(destination, srcProp.GetValue(source, null), null);
    }
}

以下是我在上述评论中谈到的方法。

另请参阅此链接:Apply properties values from one object to another of the same type automatically?