1
Id
、Name
、Status
のようなプロパティを持つGeneric Abstract Class
があります。このクラスはいくつかのカタログを継承します。 私の質問は、抽象クラスを実装するカタログに対して制限付きのメソッドを作成できるかどうかです。クラスが抽象クラスを実装する汎用タイプの制約
彼らは私が何をしたいのかを理解するように、私はいくつかの例を与える:
public abstract class AbsCatalog<T>
{
public T Id { get; set; }
public string Name { get; set; }
public bool Status { get; set; }
}
はこれらは私が実装する方法は以下の通りですabstract class
public class Agent : AbsCatalog<string>
{
public string Office { get; set; }
public Estado Estado { get; set; }
}
public class Models : AbsCatalog<int>
{
public int Year { get; set; }
public string Description { get; set; }
}
を実装するクラスです
List<Agent> Agents = service.GetAgents();
string AgentsDescription = GetDescription<Agent>(Agents);
List<Model> Models = service.GetModels();
string ModelsDescription = GetDescription<Model>(Models);
private string GetDescription<T>(List<T> list) where T : AbsCatalog<T>
{
string description = string.Empty;
if (list.Exists(x => x.Id.ToString() == "0"))
description = "";
else
description = string.Join(", ", list.Where(x => x.Status).Select(x => x.Name).ToArray());
return description;
}
しかし、検証では、エラーをマーク: '場合(list.Exists(X => x.Id .ToString()== "0")) ' IDはUタイプ – Richard
なので、すべてがToStringを持つ' object'から継承するので、エラーにはなりません。また、 '==" 0 "'をチェックするのではなく、 'default(U)'を使うか、メソッドにデフォルト値を渡してください。 – DavidG