问题
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;
}
}
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.
However, with Method B you cannot assign the same object directly to this.
Or is there another way to do this?
回答1:
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.
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;
回答2:
/// <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);
}
}
Here's that method I talked about in the comments above.
Also refer to this link: Apply properties values from one object to another of the same type automatically?
来源:https://stackoverflow.com/questions/33392575/how-to-assign-to-all-class-data-members-at-once