1

プロジェクトを通過し、特別な属性を持つクラスを検索し、ClassName.PropertyName とプロパティ内の ResourceManager.GetValue に渡される文字列の 2 つの情報を収集できるリフレクション コードを作成するにはどうすればよいですか。私のコードは次のとおりです。助けてください。ありがとう

    [TestMethod]
    public void TestMethod1()
    {

        Dictionary<string, string> mydictionary = new Dictionary<string, string>();
        mydictionary = ParseAllClassesWithAttribute("MyAttribute");

        Assert.AreEqual(mydictionary["MyClass.FirstNameIsRequired"].ToString(), "First Name is Required");


    }

    private Dictionary<string, string> ParseAllClassesWithAttribute(string p)
    {
        Dictionary<string,string> dictionary = new Dictionary<string, string>();

        // use reflection to go through the class that is decorated by attribute MyAttribute
        // and is able to extract ClassName.PropertyName along with what is Inside
        // GetValue method parameter.
        // In the following I am artificially populating the dictionary object.

        dictionary.Add("MyClass.FirstNameIsRequired", "First Name is Required");
        return dictionary;
    }



     [MyAttribute]
     public class MyClass
        {
            public string FirstNameIsRequired
            {
                get
                {
                    return ResourceManager.GetValue("First Name is required");
                }
            }
        }

        public static class ResourceManager
        {
            public static string GetValue(string key)
            {
                return String.Format("some value from the database based on key {0}",key);
            }
        }
4

1 に答える 1

1

"First Name is Required"ILバイトを取得して解析しない限り、リフレクションは値を抽出できません。考えられる解決策の 1 つを次に示します。

[AttributeUsage(AttributeTargets.Property)]
public class MyAttribute : Attribute
{
    public string TheString { get; private set; }
    public MyAttribute(string theString)
    {
        this.TheString = theString;
    }
}

const string FirstNameIsRequiredThing = "First Name is required";
[MyAttribute(FirstNameIsRequiredThing)]
public string FirstNameIsRequired
{
    get
    {
        return ResourceManager.GetValue(FirstNameIsRequiredThing);
    }
}

これで、すべてのプロパティを読み取りMyAttribute、期待値を確認できます。(この部分に問題がある場合は、質問のコメントのアドバイスに従ってください)

于 2012-07-04T00:06:44.163 に答える