私がこのお持ちの場合:私は、文字列として"System.Collections.Generic.Dictionary"
取得するにはどうすればよい.NETでジェネリック型のベース名を取得する正しい方法は、サブストリングですか?
Type t = typeof(Dictionary<String, String>);
を?これを行うための最善の方法です:
String n = t.FullName.Substring(0, t.FullName.IndexOf("`"));
私はちょっとハックします。
私がこれを望む理由は、Type
オブジェクトを取得して、C#ソースコードファイルにあるコードに似たコードを生成したいからです。私はいくつかのテキストテンプレートを作成しています、と私はソースの中に文字列としてタイプを追加する必要がある、とFullName
プロパティは、このような生成します。代わりに私が何をしたいの
System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089]]
:
System.Collections.Generic.Dictionary<System.String, System.String>
を
編集は:[OK]を、ここでの最終的なコードは、だ、まだ私には少しハックのように思えるが、それは動作します:
/// <summary>
/// This method takes a type and produces a proper full type name for it, expanding generics properly.
/// </summary>
/// <param name="type">
/// The type to produce the full type name for.
/// </param>
/// <returns>
/// The type name for <paramref name="type"/> as a string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="type"/> is <c>null</c>.</para>
/// </exception>
public static String TypeToString(Type type)
{
#region Parameter Validation
if (Object.ReferenceEquals(null, type))
throw new ArgumentNullException("type");
#endregion
if (type.IsGenericType)
{
if (type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
Type underlyingType = type.GetGenericArguments()[0];
return String.Format("{0}?", TypeToString(underlyingType));
}
String baseName = type.FullName.Substring(0, type.FullName.IndexOf("`"));
return baseName + "<" + String.Join(", ", (from paramType in type.GetGenericArguments()
select TypeToString(paramType)).ToArray()) + ">";
}
else
{
return type.FullName;
}
}
正しいが、私は示したように、サブストリングを使用して、汎用パーツ前に名前の一部を取得する唯一の方法であります、または私が知りませんプロパティやメソッドは、反射的な方法があるか? –
JohannesHが彼の答えで指摘しているように、あなたが見るのはIL表記です。他のもの(C#のようなもの)が必要な場合は、自分でマップする必要があります。私たちはあなたが提案しているものに似た何かをする社内ツールをいくつか持っています。私はC#の構文を取得する他の方法を認識していませんが、一方で私はフォーマットが固定されていると仮定し、あなたはそれをあなた自身で安全に変換できるはずです。 –