Skip to content

Instantly share code, notes, and snippets.

@matarillo
Last active August 29, 2015 14:00
Show Gist options
  • Select an option

  • Save matarillo/2ed2c34c2165c6baff24 to your computer and use it in GitHub Desktop.

Select an option

Save matarillo/2ed2c34c2165c6baff24 to your computer and use it in GitHub Desktop.

#02 ジェネリクス型変数と型階層 ... のC#版

C# でもJavaと同じ。

型変数の消去とか追加とか

同じ。

public interface Executor<I, O>
{
	O Exec(I input);
}

public class SumInteger : Executor<IList<int>, int>
{
	public int Exec(IList<int> input)
	{
		int ret = 0;
		foreach (var value in input)
		{
			ret += value;
		}
		return ret;
	}
}

public interface HashCodeExecutor<I> : Executor<I, int>
{
}

public class StringHashCodeExecutor : HashCodeExecutor<string>
{
	public int Exec(string input)
	{
		return input.GetHashCode();
	}
}

public interface MapExecutor<K, V, O> : Executor<IDictionary<K, V>, O>
{
}

public interface ExExecutor<I, O, X1, X2, X3> : Executor<I, O>
{
}

型変数の境界の変更

同じ。

public class A
{
}

public class B : A
{
}

public class C : B
{
}

public class Hoge<T> where T : A
{
}

public class Hoge2<T2> : Hoge<T2> where T2 : B
{
}

public class Hoge3<T3> : Hoge2<T3> where T3 : C
{
}

複雑な境界

唯一の違いは、Hoge<X, V, T>のように、型パラメータXが必要なこと。 (追記)Javaでも同様だったみたい。

public interface IValue<X, V, T>
	where V : IValue<X, V, T>
	where T : IValueType<X, V, T>
{
	T ValueType { get; }
	X Value { get; }
}

public interface IValueType<X, V, T>
	where V : IValue<X, V, T>
	where T : IValueType<X, V, T>
{
	V Max { get; }
	V Min { get; }
}

public class Hoge<X, V, T>
	where V : IValue<X, V, T>
	where T : IValueType<X, V, T>
{
}

/** Integer型を表現するクラス */
public class IntegerValueType : IValueType<int, IntegerValue, IntegerValueType>
{
	private static readonly IntegerValue _maxValue = new IntegerValue(int.MaxValue);
	private static readonly IntegerValue _minValue = new IntegerValue(int.MinValue);

	public IntegerValue Max { get { return _maxValue; } }
	public IntegerValue Min { get { return _minValue; } }
}

/** Integerの値を表現するクラス */
public class IntegerValue : IValue<int, IntegerValue, IntegerValueType>
{
	private static readonly IntegerValueType _type = new IntegerValueType();
	private int _value;

	public IntegerValue(int value)
	{
		_value = value;
	}

	public IntegerValueType ValueType { get { return _type; } }
	public int Value { get { return _value; } }
}

public class IntegerHoge<V, T>
	where V : IntegerValue
	where T : IntegerValueType
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment