int、stringなどの標準データ型にいくつかのプロパティを追加するためのコンテナクラスがあります。このコンテナクラスは、そのような(標準タイプの)オブジェクトのオブジェクトをカプセル化します。他のクラスは、追加されたプロパティを取得/設定するためにコンテナクラスのサブクラスを使用します。ここで、サブクラスが、追加のコードを含まずに、カプセル化されたオブジェクトとそれ自体の間で暗黙的にキャストできるようにします。
これが私のクラスの簡単な例です:
// Container class that encapsulates strings and adds property ToBeChecked
// and should define the cast operators for sub classes, too.
internal class StringContainer
{
protected string _str;
public bool ToBeChecked { get; set; }
public static implicit operator StringContainer(string str)
{
return new StringContainer { _str = str };
}
public static implicit operator string(StringContainer container)
{
return (container != null) ? container._str : null;
}
}
// An example of many sub classes. Its code should be as short as possible.
internal class SubClass : StringContainer
{
// I want to avoid following cast operator definition
// public static implicit operator SubClass(string obj)
// {
// return new SubClass() { _str = obj };
// }
}
// Short code to demosntrate the usings of the implicit casts.
internal class MainClass
{
private static void Main(string[] args)
{
SubClass subClass = "test string"; // ERROR: Cannot convert source type 'string' to 'SubClass'
string testString = subClass; // No error
}
}
私の実際のコンテナクラスには2つの型パラメータがあります。1つはカプセル化されたオブジェクトの型(string、int、...)用で、もう1つはサブクラス型(SubClassなど)用です。
どうすればコードを作成できますか
SubClass subClass = "test string"; // ERROR: Cannot convert source type 'string' to 'SubClass'
サブクラスの最小限のコードで実行可能ですか?