代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace test
{
public class Brother
{
public Brother()
{
}
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
public Brother this[int index]
{
get
{
if (index == 0)
{
return new SmallBro();
}
else
{
return new BigBro();
}
}
}
public virtual void Talk()
{
}
}
public class SmallBro : Brother
{
public override void Talk()
{
Console.Write("smallbrother age:"+Age.ToString());
}
}
public class BigBro : Brother
{
public override void Talk()
{
Console.Write("bigbrother age:" + Age.ToString());
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace test
{
class Program
{
static void Main(string[] args)
{
Brother b = new Brother();
b.Age = 11;
b[0].Talk();
Console.Read();
}
}
}
谢谢 困扰了我
需要根本解决 不通过函数传参
------解决思路----------------------
要么你就这样子
里面就不受子类限制了,可以在未知子类的情况下,使用
class Program
{
static void Main(string[] args)
{
Brother b = new Brother();
b.Age = 11;
b.Child<SmallBro>().Talk();
Console.ReadLine();
}
}
public class Brother
{
public Brother()
{
}
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
public T Child<T>() where T : Brother, new()
{
T obj = new T();
obj._age = this._age;
return obj;
}
public virtual void Talk()
{
}
}
public class SmallBro : Brother
{
public override void Talk()
{
Console.Write("smallbrother age:" + Age.ToString());
}
}
public class BigBro : Brother
{
public override void Talk()
{
Console.Write("bigbrother age:" + Age.ToString());
}
}
------解决思路----------------------
以前我们说对于OO学习的比较差的人,总是以为子类对象中有一个对象实例是父类类型的,也就是以为 SmallBro 对象实例内部还有另外一个对象被实例为 Brother 类型的,由此造成了一堆诡异的想法。
现在我知道这种想法也不过是“小问题”,可以看成简单的“技术性问题”了。因为我真的没有想到,还有人会更离谱地以为父类对象内部要住着各种子类对象的各种实例?
你千万不要往下学习OO了。先把概念想明白。如果人家.net 中定义一个类型叫做Control,难道它要把未来的几千种控件都要先在 Control 类型中写一遍?而且要把将来由用户定义的各种Control也预先写一遍?这显然是本末倒置的。
------解决思路----------------------
也不要什么父类根据索引返回特定子类了
按你需求,定义枚举,然后建立简单工厂,根据枚举返回子类就行了,何苦这么折腾,将来你要扩展也方便,只要修改枚举就可以
------解决思路----------------------
楼上说的对,用静态方法返回类的实例就行
?Brother b=Factory.Create(不同的枚举返回不同的实例)
------解决思路----------------------
楼主是否需要的是一个工厂
public abstract class Brother
{
public int Age
{
get;
set;
}
public static Brother CreateBro(BroType bType)
{
Brother bro = null;
switch (bType)
{
case BroType.Big:
bro = new BigBro();
break;
case BroType.Small:
break;
default:
throw new NotImplementedException();
}
return bro;
}
public abstract void Talk();
}
public class SmallBro : Brother
{
public override void Talk()
{
Console.Write("smallbrother age:"+Age.ToString());
}
}
public class BigBro:Brother
{
public override void Talk()
{
Console.Write("bigbrother age:" + Age.ToString());
}
}
public enum BroType
{
None =0 ,
Small =1,
Big = 2,
}
调用工厂创建需要的实例
class Program
{
static void Main(string[] args)
{
Brother b = Brother.CreateBro(BroType.Big);
b.Age = 11;
b.Talk();
Console.Read();
}
}