を使用して属性を取得しますか?線に沿って:は形で私のプロジェクトで繰り返しコードを考えるとジェネリック
The type parameter <T> cannot be used with the `as` operator because it does not have a class type constraint nor a `class` constraint.
を使用して属性を取得しますか?線に沿って:は形で私のプロジェクトで繰り返しコードを考えるとジェネリック
The type parameter <T> cannot be used with the `as` operator because it does not have a class type constraint nor a `class` constraint.
簡単、ちょうどT
はAttribute
から継承しなければなりませんと言う型の制約を置く:
public static T GetAttribute<T, T1>(T1 value)
{
var type = value.GetType();
var name = Enum.GetName(type, value);
if (name == null) return default(T);
var field = type.GetField(name);
if (field == null) return default(T);
return Attribute.GetCustomAttribute(field, typeof(T)) as T;
}
私は戻りライン上のエラーを取得します。
public static T GetAttribute<T>(object value)
where T : Attribute
{
var type = value.GetType();
var name = Enum.GetName(type, value);
if (name == null) return default(T);
var field = type.GetField(name);
if (field == null) return default(T);
return Attribute.GetCustomAttribute(field, typeof(T)) as T;
}
T1
はまったく必要ありません。何でもGetType()
に電話することができます(もちろんnull
は除く)。 T1
をメソッドの本体に使用したことはありません。そのため、パラメータがどのタイプであるかは問題ではありません。
where T : class
でも、あなたは誰も念のためにGetAttribute<String>()
を呼び出すようにコンパイラを参加させるかもしれません。
メソッド定義にwhere T : class
を追加しないでください。コードはT canがクラスであり、インスタンス化できることを知っていますか?
public static T GetAttribute<T, T1>(T1 value) where T : class
{
var type = value.GetType();
var name = Enum.GetName(type, value);
if (name == null) return default(T);
var field = type.GetField(name);
if (field == null) return default(T);
return Attribute.GetCustomAttribute(field, typeof(T)) as T;
}
私よりもはるかに良い答えです。良い仕事先生:-) – Wndrr