转换泛型类型然后使用Ref
本文关键字:Ref 然后 泛型类型 转换 | 更新日期: 2023-09-27 17:50:36
我需要弄清楚我的问题。
我有这样一个方法:
public static void SetEntityValue<TEntity>(ref TEntity entityToTransform, PropertyHelper entityProperty)
{
// create type from entity
Type t = entityToTransform.GetType();
// get the property to set
var prop = t.GetProperty(entityProperty.Name);
// set the property value to the one parsed
prop.SetValue(entityToTransform, entityProperty.Value, null);
}
PropertyHelper
只包含两个属性,Name和Value。
所以,我有一个方法,它接受一个泛型类型,然后需要初始化一个新的,并填充它的属性值,这个方法会这样做吗:
TEntity ReadIntoEntity<TEntity>(TEntity entity, XElement node)
{
if (!node.HasElements)
throw new IllFormedDocumentException("Entity found but contains no properties");
var xmlProps = node.Elements();
Type t1 = entity.GetType();
// the line which initialises a new TEntity same as string myString = new string();
TEntity newEntity = Activator.CreateInstance<TEntity>();
var props = t1.GetProperties();
var readableProps = props.Select(x => new PropertyHelper(GenericHelper.GetEntityProperty(x), GenericHelper.GetEntityValueAsObject<TEntity>(entity, x)));
List<string> foundAProp = new List<string>();
foreach (var el in xmlProps)
{
// iterate through all xml elements
foreach (var prop in readableProps)
{
// check the prop exists in the xml set
// We found a prop that exists!
if (el.Name.ToString() == prop.Name.ToString())
{
foundAProp.Add(prop.Name.ToString());
GenericHelper.SetEntityValue<TEntity>(ref newEntity, prop);
}
}
}
}
会像非泛型那样工作吗?
MyEntity ReadIntoEntity(XElement node)
{
if (!node.HasElements)
throw new IllFormedDocumentException("Entity found but contains no properties");
var xmlProps = node.Elements();
MyEntity newEntity = new MyEntity();
var props = typeof(MyEntity).GetProperties();
var readableProps = props.Select(x => new PropertyHelper(GenericHelper.GetEntityProperty(x), GenericHelper.GetEntityValueAsObject<TEntity>(entity, x)));
List<string> foundAProp = new List<string>();
foreach (var el in xmlProps)
{
// iterate through all xml elements
foreach (var prop in readableProps)
{
// check the prop exists in the xml set
// We found a prop that exists!
if (el.Name.ToString() == prop.Name.ToString())
{
foundAProp.Add(prop.Name.ToString());
GenericHelper.SetEntityValue<MyEntity>(ref newEntity, prop);
}
}
}
}
So effective is:
TEntity newEntity = Activator.CreateInstance<TEntity>();
等价于:
MyEntity newEntity = new MyEntity();
谢谢
这个方法会做这件事吗?
然而:TEntity newEntity = Activator.CreateInstance<TEntity>();
应替换为
TEntity newEntity = new TEntity();
在为参数添加new()
泛型约束后。这将添加编译时检查,以确保实体具有有效的无参数构造函数。例如:
TEntity ReadIntoEntity<TEntity>(TEntity entity, XElement node)
where TEntity : class, new()
{
// ...
你不需要ref
在你的第一个方法中,假设你所有的实体都是class
类型。