2017-02-26 14 views
0

System.Attributeから継承した非常に基本的なクラスライブラリがあります。私はアセンブリとして署名して、dllを別のプログラムで使用できるようにしました。C#外部クラスライブラリの属性

namespace BearData 
{ 
    public class BearData : Attribute 
    { 
    private string[] array1; 
    private string bear = "Bear"; 
    private int weight; 

    public BearData(string bear) 
    { 
     this.bear = bear; 
    } 
    public string Bear 
    { 
     get 
     { 
      return bear; 
     } 

     set 
     { 
      bear = value; 
     } 
    } 

    public int Weight 
    { 
     get 
     { 
      return weight; 
     } 

     set 
     { 
      weight = value; 
     } 
    } 

    public string[] BearTypes() 
    { 
     array1 = new string[8]; 
     array1[0] = "Brown/Grizzly"; 
     array1[1] = "Polar"; 
     array1[2] = "Asian Black"; 
     array1[3] = "American Black"; 
     array1[4] = "Sun"; 
     array1[5] = "Sloth"; 
     array1[6] = "Spectacled"; 
     array1[7] = "Giant Panda"; 

     return array1; 
    } 
    } 
} 

ここでは、基本的なコンソールアプリケーションで使用されます。タイプの

bearAttribute = (BearData.BearData)attrs[0]; 

」未処理の例外 ':しかし原因私の教授の、不可解な漠然とした、そして謎めいた性質のために、私はこのラインからのエラーを取得するwork.Iにこれを得ることにまだスタンドによSystem.IndexOutOfRangeException ' がAssigntment5_Console.exeで発生しました。'は正確なエラーです。

このエラーの原因は何ですか?

さらに一般的には、これは外部のライブラリからの属性を使用するための適切な方法ですか?私には不思議なことに、ランダムな配列がここにスローされ、アトリビュートクラスに配列をキャストしているということがありますか?

ところで、これは私の教授が単一のVisual Studioインスタンスで分離された属性クラスのコードを書いた方法です。彼はまた、エクスポートクラスライブラリDLLの例を持っていたし、私はあなたがProgram.Main()メソッドにBearData属性を定義しているか2.

using BearData; 
namespace Assigntment5_Console 
{ 
    class Program 
    { 

    [BearData.BearData("Bear", Weight = 1000)] 

    static void Main(string[] args) 
    { 
     MemberInfo attributeInfo; 
     attributeInfo = typeof(BearData.BearData); 
     object[] attrs = attributeInfo.GetCustomAttributes(false); 

     //for (int i = 0; i < attrs.Length; i++) 
     //{ 
     // Console.WriteLine(attrs[i]); 
     //} 
     BearData.BearData bearAttribute; 
     bearAttribute = (BearData.BearData)attrs[0]; 


     Console.WriteLine("Animal: " + bearAttribute.Bear + "\nAverage Weight: " + bearAttribute.Weight); 
     Console.ReadLine(); 
    } 


    } 
} 

答えて

1

を組み合わせることを把握するために自分のデバイスに残っていましたあなたは、次のコードは間違いなく、それは最初の試みを仕事に手に入れたあなたの問題

namespace Assigntment5_Console 
{ 
    class Program 
    { 
     [BearData.BearData("Bear", Weight = 1000)] 
     static void Main(string[] args) 
     { 
      MethodBase method = MethodBase.GetCurrentMethod(); 
      object[] attrs = method.GetCustomAttributes(typeof(BearData.BearData), true); 

      BearData.BearData bearAttribute; 
      bearAttribute = (BearData.BearData)attrs[0]; 

      Console.WriteLine("Animal: " + bearAttribute.Bear + "\nAverage Weight: " + bearAttribute.Weight); 
      Console.ReadLine(); 
     } 
    } 
} 
+1

を修正する必要が

属性を探しているべきです。どうもありがとう! –

関連する問題