Мне нужно динамически привести свойство к его фактическому типу. Как я / могу ли я сделать это с помощью отражения?
Чтобы объяснить реальный сценарий, над которым я работаю, немного. Я пытаюсь вызвать «Первый» метод расширения для свойства Entity Framework. Конкретное свойство, вызываемое для объекта контекста Framework, передается методу в виде строки (а также идентификатора извлекаемой записи). Поэтому мне нужен фактический тип объекта для вызова метода First.
Я не могу использовать метод «Где» для объекта, поскольку лямбда-метод или метод делегата все еще нуждаются в фактическом типе объекта для доступа к свойствам.
Также, поскольку объект генерируется Entity Framework, я не могу привести тип к интерфейсу и работать с ним.
Это код сценария:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
namespace NmSpc
{
public class ClassA
{
public int IntProperty { get; set; }
}
public class ClassB
{
public ClassA MyProperty { get; set; }
}
public class ClassC
{
static void Main(string[] args)
{
ClassB tester = new ClassB();
PropertyInfo propInfo = typeof(ClassB).GetProperty("MyProperty");
//get a type unsafe reference to ClassB`s property
Object property = propInfo.GetValue(tester, null);
//get the type safe reference to the property
ClassA typeSafeProperty = property as ClassA;
//I need to cast the property to its actual type dynamically. How do I/Can I do this using reflection?
//I will not know that "property" is of ClassA apart from at runtime
}
}
}
У меня было некоторое время, поэтому я попытался решить свою проблему, используя VS2010, и я думаю, что был прав ранее, когда я думал, что динамическая клавиатура «решит» мой вопрос. Смотрите код ниже.
using System.Reflection;
namespace TempTest
{
public class ClassA
{
public int IntProperty { get; set; }
}
public class ClassB
{
public ClassB()
{
MyProperty = new ClassA { IntProperty = 4 };
}
public ClassA MyProperty { get; set; }
}
public class Program
{
static void Main(string[] args)
{
ClassB tester = new ClassB();
PropertyInfo propInfo = typeof(ClassB).GetProperty("MyProperty");
//get a type unsafe reference to ClassB`s property
dynamic property = propInfo.GetValue(tester, null);
//casted the property to its actual type dynamically
int result = property.IntProperty;
}
}
}
public object CastPropertyValue(PropertyInfo property, string value) {
if (property == null || String.IsNullOrEmpty(value))
return null;
if (property.PropertyType.IsEnum)
{
Type enumType = property.PropertyType;
if (Enum.IsDefined(enumType, value))
return Enum.Parse(enumType, value);
}
if (property.PropertyType == typeof(bool))
return value == "1" || value == "true" || value == "on" || value == "checked";
else if (property.PropertyType == typeof(Uri))
return new Uri(Convert.ToString(value));
else
return Convert.ChangeType(value, property.PropertyType); }