adressmoeistranici
@adressmoeistranici
Делатель

Как правильно реализовать IEnumerable для обобщенного класса?

Объясните пожалуйста из за чего ошибки?
public class GenericArray<T, S>: IEnumerable where T: ItemGenericArray<S>
{
	private T[] objs;
	public GenericArray() 
	{
		objs = null;
	}
	public GenericArray(S[] n)
	{
		objs = new T[n.Length];
		for (int i = 0; i < n.Length; i++)
			objs [i] = new T(n[i]);//Cannot create an instance of the variable type `T' because it does not have the new() constraint , `T': cannot provide arguments when creating an instance of a variable type
	}
	public int Length
	{
		get { return objs.Length; }
	}
	public S[] ToSystemArray()
	{
		if (objs != null) 
		{
			S[] t = new S[objs.Length];
			for (int i = 0; i < t.Length; i++)
				t [i] = objs[i].obj;
			return t;
		} 
		else
			return null;
	}
	public T this[int index]
	{
		get 
		{
			return objs[index];
		}
		set
		{
			objs[index] = value;
		}
	}
	IEnumerator IEnumerable.GetEnumerator()
	{
		for (int i = 0; i < objs.Length; i++) 
		{
			yield return objs[i];
		}
	}
	public IEnumerable GetEnumeratorPage(int max)
	{
		for (int i = 0; i < max; i++) 
		{
			if (i == objs.Length) 
			{
				yield break;
			}
			else
				yield return objs[i];
		}
	}
}
public class ItemGenericArray<S>
{
	public S obj { get; set; }
	public ItemGenericArray(S obj)
	{
		this.obj = obj;
	}
}
public class ItemAssetObjectGenericArray: ItemGenericArray<Object>
{
	public static ObjectSorter.namerAction na;
	public static string directory;
	public Object Obj 
	{
		get 
		{
			return obj;
		} 
		set 
		{ 
			string path = AssetDatabase.GetAssetPath(value);
			if (!string.IsNullOrEmpty(path) && path.Contains(directory)) 
			{
				char[] splitter = { '/' };
				string[] dirs = path.Split(splitter);
				if (na == ObjectSorter.namerAction.sortableFiles) 
				{
					if (dirs.Length == 4 && (new Regex(@"№\d{4}\..*\.\w*$").Matches(dirs[dirs.Length - 1]).Count) == 1) 
					{
						if (dirs[dirs.Length - 1].Contains (".jpg") || dirs[dirs.Length - 1].Contains (".png") || dirs[dirs.Length - 1].Contains (".mpeg") || dirs[dirs.Length - 1].Contains (".ogg")) 
						{
							obj = value;
						}
					}
				} 
				else 
				{
					if (dirs.Length == 3 && (new Regex(@"№\d{4}\..*$").Matches(dirs[dirs.Length - 1]).Count) == 1) 
					{
						obj = value;
					} 
				}
			}
		}
	}
	public ItemAssetObjectGenericArray(Object o) : base(o) 	{	}
}
  • Вопрос задан
  • 221 просмотр
Решения вопроса 1
Nipheris
@Nipheris Куратор тега C#
С параметром в к-ре ничего не получится, это ограничения языка, то что вы не можете потребовать от типа T конструктора с параметрами (можно только без параметров). Передавайте в ваш класс функцию-фабрику для значений/объектов типа T.

И да, реализуйте прежде всего IEnumerable а не только IEnumerable.
Ответ написан
Пригласить эксперта
Ответы на вопрос 2
alexsandr0000
@alexsandr0000
Программист C#/C++/C
Это ограничение, T должен реализовывать эти интерфейсы
Ответ написан
@DarkByte2015
public class GenericArray<T, S>: IEnumerable where T: ItemGenericArray<S>

ienumerable здесь подключенный интерфейс или ограничение?

ограничение
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы