如何获取具有泛型 typeof 的字段的值
How do I get the value of a field with generic typeof
鉴于我有一个参数 TEntity
,它将是一个 class,我如何获取其中一个字段的值。
public class ProductStrategy<TContract> : IContractCreatorStrategy<TContract>
{
public IContract<TContract> CreateContract<TEntity>(TEntity dbEntity)
{
var productEntity = Convert.ChangeType(dbEntity, typeof(TEntity));
var contractType = typeof (TContract);
var entityType = dbEntity.GetType();
var contract = Activator.CreateInstance(contractType);
var contractFields = contractType.GetProperties().ToList();
var entityFields = entityType.GetProperties().ToList();
foreach (var contractField in contractFields)
{
foreach (var entityField in entityFields)
{
if (entityField.Name.Contains(contractField.Name))
{
//get the value of the entityfield and set the contract field value to the it.
}
}
}
return new ProductContract<TContract>();
return productContract;
}
}
var fieldValue = entityField.GetValue(dbEntity, null);
contractField.SetValue(contract, fieldValue);
鉴于我有一个参数 TEntity
,它将是一个 class,我如何获取其中一个字段的值。
public class ProductStrategy<TContract> : IContractCreatorStrategy<TContract>
{
public IContract<TContract> CreateContract<TEntity>(TEntity dbEntity)
{
var productEntity = Convert.ChangeType(dbEntity, typeof(TEntity));
var contractType = typeof (TContract);
var entityType = dbEntity.GetType();
var contract = Activator.CreateInstance(contractType);
var contractFields = contractType.GetProperties().ToList();
var entityFields = entityType.GetProperties().ToList();
foreach (var contractField in contractFields)
{
foreach (var entityField in entityFields)
{
if (entityField.Name.Contains(contractField.Name))
{
//get the value of the entityfield and set the contract field value to the it.
}
}
}
return new ProductContract<TContract>();
return productContract;
}
}
var fieldValue = entityField.GetValue(dbEntity, null);
contractField.SetValue(contract, fieldValue);