0

すでに仕事をしているメソッドを変換したい

(クラスをその本体内でインスタンス化する場合のみ)

対象のクラスを渡されたパラメータとして受け入れるものに...どういうわけか。

私は試行錯誤によって自分でその結果を得ようとしました(主に試行錯誤、たくさん...)

しかし成功しません(:

この最初のクラスは私のヘルパークラス(拡張名前空間)内にあります

public static List<string> AnyClassFieldsValuesAsList<T>(this T Clss, string nestedName)
{
    // i know how to get this to work... if an instace of the class is declared 
    // only here i would like to have any given class...as passed parameter
    // couple of tests to get a hold of the passed Class...no success (:
    var T1 = typeof(T.GetType());
    var T2 = Clss.GetType();

    return typeof(Clss.GetType()).GetFields(); //ToList<string>();
}

これは、スタイルフォントを表す文字列を保持するための対象クラス(同じヘルパーファイルに保存したもの)です。

public class FontNames 
{
    public readonly string Aharoni = "Aharoni",
                           Andalus = "Andalus",
                           AngsanaNew = "Angsana New",
                           AngsanaUPC = "AngsanaUPC",
                           Aparajita = "Aparajita";
                           //.....etc'
}

現在のプロジェクトの背後にあるコード内で、次のようなことができるようになりたい

//imports of extensions and my style namespaces ....
// then somewhere after Page_Load()...

var instnceOfFnames  = new FontNames();
list<string> FontsLst= instnceOfFnames.AnyClassFieldsValuesAsList(.....);

上部の署名のパラメータはAnyClassFieldsValuesAsList()テスト用ですが、

私は彼らと一緒に働くことができなかったので、私は彼らが私が合格すべきものであるかどうかわかりません。

結果を達成するための正しい構文は何ですか?

4

1 に答える 1

2

私が理解している限り、クラスのインスタンスなしでフィールドの値を取得する必要があります。これらのフィールドをとして宣言する必要があると思いますpublic readonly static ...。その後、次の方法を利用できるようになります。

public static IEnumerable<string> GetFields<T>()
{
    Type type = typeof(T);
    return type.GetFields(BindingFlags.Static | BindingFlags.Public)
                .Where(f => f.FieldType == typeof(string))
                .Select(f => (string)f.GetValue(null));
}

このような:

foreach (string f in GetFields<FontNames>())
     Console.WriteLine(f);

コメントに基づく:

現在の問題(私が理解している限り)では、静的フィールドにインスタンスにアクセスする必要がないため、これは過剰な問題のようです。しかし、少なくともそれはいくつかのアイデアを与えることができます

public static IEnumerable<string> GetFields<T>(this T value)
{
    Type type = value.GetType();
    //...all the same as above
}

同じ結果を得るには、ジェネリックなしで同じ結果を得るだけで十分です

public static IEnumerable<string> GetFields(this object value)
{
    Type type = value.GetType();
    //...all the same as above
}
于 2012-12-16T01:53:01.190 に答える