我有一个小问题。
我的问题是以下。如何将对象反映到仅在运行时已知类型
我有两种类型:AssetData和AssetData。它们基本相同,但不是遗传的。
现在我已经知道类型为“AssetData”的属性,并且我有一个AssetData类型的对象(包含一个Texture2D对象)。
现在我想将AssetData对象转换为AssetData对象。因为我不知道通用参数,所以AssetData现在具有该类型转换的操作符,但AssetData可以转换为AssetData。
我试过并试过我能做的事来解决它,但我没有更多的想法。
这是我的情况:我有一个属性类型,我有一个AssetData具有相同的对象,但我必须将AssetData设置为属性 - 所以我必须设置“AssetData”,而不是AssetData 。
这是我的代码。我无法对其进行硬编码,因为在添加新类型之后要更改这些内容。这是我最近的尝试。它几乎工程,但有投不工作的问题,因为没有there's的AssetData操作...
foreach (PropertyInfo pinf in comp.GetType().GetProperties())
{
for (int i = 0; i < cdata.PInf.Count; i++)
{
if (cdata.PInf[i] != pinf.Name) continue;
AssetData assetData = new AssetData
{
AssetName = cdata.AN[i],
AssetType = Type.GetType(cdata.AT[i], true)
};
Application.Game.GetSystem<ContentManager>().LoadContent(ref assetData);
if (pinf.PropertyType.IsGenericType)
{
MethodInfo method = typeof (DynamicCast).GetMethod("Cast").GetGenericMethodDefinition().MakeGenericMethod(
assetData.AssetType);
Type castedAssetType =
pinf.PropertyType.GetGenericTypeDefinition().MakeGenericType(assetData.AssetType);
dynamic castedAsset = method.Invoke(typeof (DynamicCast), new[] {assetData});
pinf.SetValue(comp, castedAsset, null);
}
}
}
}
而且here's“DynamicCast”的方法 - 这是我上的博客上发现。这也doesn't工作...
public static class DynamicCast
{
public static T Cast<T>(object o)
{
Type ot = o.GetType();
MethodInfo meth = GetMethod(ot, "op_Implicit", typeof(T),
BindingFlags.Static | BindingFlags.Public);
if (meth == null)
{
meth = GetMethod(ot, "op_Explicit", typeof(T),
BindingFlags.Static | BindingFlags.Public);
}
if (meth == null) throw new InvalidCastException("Invalid Cast.");
return (T) meth.Invoke(null, new[] {o});
}
public static MethodInfo GetMethod(Type toSearch, string methodName,
Type returnType, BindingFlags bindingFlags)
{
return Array.Find(
toSearch.GetMethods(bindingFlags),
inf => ((inf.Name == methodName) && (inf.ReturnType == returnType)));
}
}
的问题是,我必须创建一个AssetData对象(在这种情况下),并将其设置为属性值。但是对象很清楚,所以我必须将AssetData的“Asset”属性投射到“AssetData”。两者都是相同的类型,但一个是“对象”和一个“T”(Texture2D)。
我该如何施展?
非常感谢!我从中午开始工作......
埃姆,它doesn't工作。但请等待几分钟。我正在尝试一些不同的... – SharpShade 2011-04-09 21:46:57
本来可以很好的提到,这需要C#4.0和DLR – sehe 2011-04-09 22:37:28
@sehe:我还应该提到,这需要一个编译器吗?而且它需要一台电脑?来吧。 – Timwi 2011-04-10 19:10:37