のキャストは、私がキャストしようとすると、例外がスローされると、次のシナリオを持っている:反射と
- 私はプロジェクト参照を追加し、プロジェクトの名前空間をインポートしました。
- LoadFile行は、このプロジェクトのビルド時に生成されたdllをロードします。
- dllからオブジェクトのプロパティをデコレートする属性のパブリックフィールドにアクセスしようとしています。ここで
- は例外テキストです:
[A] MyNamespace.PropertyMetaDataAttributeは、[B] MyNamespace.PropertyMetaDataAttributeにキャストすることはできません。タイプAは、場所 'C:\ projectA \ bin \ debug \ A.dll'のコンテキスト 'LoadFrom'に 'A、バージョン= 12.0.0.25、Culture = neutral、PublicKeyToken = null'から始まります。タイプBは、 'C:\ currentProject \ bin \ debug \ A.dll'のコンテキスト 'Default'に 'A、Version = 12.0.0.25、Culture = neutral、PublicKeyToken = null'という名前で作成されています。
コードスニペット:あなたの
ConfigurationManager.AppSettings["DLL_File_Path"]
は、他の場所で同じDLLを指しているので、.NETランタイムがすでにロードされたDLLをロードしようとするよう
using MyNamespace; // added project reference to this item
m_Assembly = Assembly.LoadFile(ConfigurationManager.AppSettings["DLL_File_Path"]);
Type objectType = m_Assembly.GetType(string.Format("{0}.{1}", NAMESPACE_PREFIX, "MyObject"));
// Crash happens on line below:
Attribute attr = (Attribute) objectType.GetProperty("Name").GetCustomAttributes(false)[0];
//This is the layout of the object which has the property
MyObject
{
[MyAttribute(Name="FooName")]
Foo {get;set;}
}
// This is the definition of the attribute
MyAttribute :Attribute
{
// Want to access the value
public string Name = string.Empty;
}