Когда эта строка bckPk = Translate (пакеты); Выполняет Я получаю Метод набора свойств не найден. ошибка, которая довольно естественна. Но может ли кто-нибудь предложить мне обходное решение для этого, которым я могу достичь того, что я пытаюсь сделать здесь?Метод определения объекта не найден
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Reflection;
namespace ExperimentProjects
{
public class ClassOne
{
public string PropertyOne { get; set; }
public string PropertyTwo { get; set; }
public string PropertyThree { get; set; }
}
public class ClassTwo
{
public string PropertyOne { get; set; }
public string PropertyTwo { get; set; }
public string PropertyThree { get; set; }
}
public class ClassPack : Collection<ClassOne>
{
}
public class ClassBckPack : Collection<ClassOne>
{
}
public class TranslateClass
{
public static TResult Translate<TSource, TResult>(TSource sourceObj)
{
Type typeOfSourceObj = sourceObj.GetType();
Type typeOfResultObj = typeof(TResult);
if (typeOfSourceObj.BaseType.Equals(typeOfResultObj.BaseType))
{
//Console.WriteLine("1");
}
ConstructorInfo constructorOfresultObj = typeOfResultObj.GetConstructor(System.Type.EmptyTypes);
Object[] parameters = new Object[0];
TResult result = (TResult)constructorOfresultObj.Invoke(parameters);
PropertyInfo[] propertiesInSourceObj = typeOfSourceObj.GetProperties();
if (propertiesInSourceObj.Length != 0)
{
foreach (PropertyInfo property in propertiesInSourceObj)
{
Console.WriteLine(property.PropertyType.Name);
PropertyInfo propertyOfResultObj = typeOfResultObj.GetProperty(property.Name);
if (propertyOfResultObj != null)
{
propertyOfResultObj.SetValue(result, property.GetValue(sourceObj));
}
}
}
Console.Read();
return result;
}
static void Main(string[] args)
{
ClassOne objOne = new ClassOne();
objOne.PropertyOne = "One";
objOne.PropertyTwo = "Two";
objOne.PropertyThree = "Three";
ClassTwo objTwo = Translate<ClassOne, ClassTwo>(objOne);
Console.WriteLine(objTwo.PropertyOne + " " + objTwo.PropertyTwo + " " + objTwo.PropertyThree);
ClassOne o = Translate<ClassOne, ClassOne>(objOne);
Console.WriteLine(o.PropertyOne + " " + o.PropertyTwo + " " + o.PropertyThree);
ClassPack packs = new ClassPack();
packs.Add(o);
packs.Add(objOne);
ClassBckPack bckPk = null;
try
{
bckPk = Translate<ClassPack, ClassBckPack>(packs);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.Read();
}
foreach (ClassOne eachObj in bckPk)
Console.WriteLine(eachObj.PropertyOne + " " + eachObj.PropertyTwo + " " + eachObj.PropertyThree);
Console.Read();
}
}
}
EDIT: Вот я хочу, чтобы скопировать объект из пакетов в bckPk с помощью отражения, не используя цикл Еогеасп. Например, возьмем этот следующий пример:
Class Content
{
}
Class AContents : Collection<Content>
{
}
Class BContents : Collection<Content>
{
}
Class BusinessEntity
{
public AContents
{
get; set;
}
}
Class DataContract
{
public AContents
{
get; set;
}
}
I want to use this Translate method this way now :
BusinessEntity be= new BusinessEntity();
DataContract dc= new DataContract();
dc=Translate<BusinessEntity,DataContract>(be);
Если я запускаю этот код, то отбросит множество свойств метод не найден ошибка
Хорошо, что вы на самом деле пытаетесь сделать? Он пытается установить свойство «Count» в этом случае ... Вы можете легко определить, доступно ли свойство для записи (используйте свойство CanWrite), но я не думаю, что это поможет вам здесь много. –
Это просто мое впечатление, но неправильно использовать такое отражение для универсального метода. В некоторых случаях это может быть необходимо, конечно. – Dirk
См. Отредактированный пост –