기본 객체를 일반 함수의 매개 변수로 사용합니다
-
05-07-2019 - |
문제
제네릭 (C# / 3.5)을 사용하여 헬퍼 방법을 구현하려고 노력하고 있습니다.
public class SomeNiceObject : ObjectBase
{
public string Field1{ get; set; }
}
public class CollectionBase<ObjectBase>()
{
public bool ReadAllFromDatabase();
}
public class SomeNiceObjectCollection : CollectionBase<SomeNiceObject>
{
}
그리고 나는 다음과 같은 일반적인 방법을 사용하여 컬렉션을 다시하고 싶습니다.
public class DAL
{
public SomeNiceObjectCollection Read()
{
return ReadFromDB<SomeNiceObjectCollection>();
}
T ReadFromDB<T>() where T : CollectionBase<ObjectBase>, new()
{
T col = new T();
col.ReadAllFromDatabase();
return col;
}
}
이것은 함께 구축되지 않습니다
Error 66 The type 'SomeNiceObjectCollection' cannot be used as type parameter 'T' in the generic type or method 'ReadFromDB<T>'. There is no implicit reference conversion from 'SomeNiceObjectCollection' to 'CollectionBase<ObjectBase>'.
신체적 요소 Collection 객체는 CollectionBase이며 정확한 수집 기반입니다. 그래서 어떻게 이것을 작동시킬 수 있습니까?
해결책
C#은 목록 유형 (공분산) 간의 주조를 지원하지 않습니다.
이 패턴을 지원하는 가장 좋은 방법은 readallfromdatabase 메소드에 대한 인터페이스를 도입하여 일반 컬렉션에 의존하지 않는 것입니다.
public class SomeNiceObject : ObjectBase
{
public string Field1{ get; set; }
}
public interface IFromDatabase
{
bool ReadAllFromDatabase();
}
public class CollectionBase<ObjectBase>() : IFromDatabase
{
public bool ReadAllFromDatabase();
}
public class SomeNiceObjectCollection : CollectionBase<SomeNiceObject>
{
}
public class DAL
{
public SomeNiceObjectCollection Read()
{
return ReadFromDB<SomeNiceObjectCollection>();
}
T ReadFromDB<T>() where T : IFromDatabase, new()
{
T col = new T();
col.ReadAllFromDatabase();
return col;
}
}
다른 팁
C# 3.0에서는 이것이 불가능하지만 공분산 및 비정규 적으로 C# 및 .NET 4.0을 사용하면 가능할 수 있습니다.
그것에 대해 생각해보십시오. 파생 된 객체가 포함 된 컬렉션을 취하고 일시적으로 기본 개체의 모음으로 취급하려고합니다. 이것이 허용되면, 기본 개체를 목록에 삽입 할 수 있으며, 이는 파생 된 객체가 아닌 목록에 있습니다.
여기서 예를 들어 :
List<String> l = new List<String>();
List<Object> o = l;
l.Add(10); // 10 will be boxed to an Object, but it is not a String!
제휴하지 않습니다 StackOverflow