WCF サービス内のリフレクションおよび DTO オブジェクトに関する他の経験とのパフォーマンスの違いを見つけることができるかどうか疑問に思っていました。Linq を使用して Entity オブジェクトから DTO オブジェクトを作成するために使用していた以下のコードがあります。
using (dashEntities context = new dashEntities())
{
result = context.GetAlerts().Select(m => new AlertItemDTO()
{
}).ToList();
別のプログラマーは、WCF サービスを構築するときに、Reflection を使用して Generic メソッドを作成し、同じ変換を行いました。
private object TransferEntityToDTO(object dto, object entity)
{
Type entityType = entity.GetType();
// Use reflection to get all properties
foreach (PropertyInfo propertyInfo in entityType.GetProperties())
{
if (propertyInfo.CanRead)
{
List<PropertyInfo> dtoProperties = dto.GetType().GetProperties().ToList();
foreach (PropertyInfo dtoProperty in dtoProperties)
{
if (dtoProperty.Name == propertyInfo.Name)
{
object value = propertyInfo.GetValue(entity, null);
if (value != null && value.ToString() != "" && value.ToString() != "1/1/0001 12:00:00 AM")
{
// This section gets the type of of the property and casts
// to it during runtime then sets it to the corresponding
// dto value:
// Get current class type
Type currentClassType = this.GetType();
//Get type of property in entity object
Type propertyType = Type.GetType(propertyInfo.PropertyType.FullName);
// Get the Cast<T> method and define the type
MethodInfo castMethod = currentClassType.GetMethod("Cast").MakeGenericMethod(propertyType);
// Invoke the method giving value its true type
object castedObject = castMethod.Invoke(null, new object[] { value });
dtoProperty.SetValue(dto, value, null);
}
break;
}
}
}
}
return dto;
}
/// <summary>
/// Used in TransferEntityToDTO to dynamically cast objects to
/// their correct types.
/// </summary>
/// <typeparam name="T">Type to cast object to</typeparam>
/// <param name="o">Object to be casted</param>
/// <returns>Object casted to correct type</returns>
public static T Cast<T>(object o)
{
return (T)o;
}
明らかに、2 番目の手法は読みにくく、より長くなりますが、より一般的であり、複数のサービスで使用できます。
私の質問は、それを汎用にする機能は、リフレクションを使用することによるパフォーマンスへの影響を上回りますか?そうでない場合、その理由は? リフレクションが高価になる理由について、多くの混乱する記事と回答を見つけました。その一部は、取得する例外がわかっているときにすべてにジェネリック例外を使用するようなもので、まだ知らないうちに必要なオブジェクトを探す必要があるためだと思います。
誰かが私のためにこれに光を当てることができますか. ありがとう