刚刚找到LinFu - 看起来非常令人印象深刻,但我不能相当看看如何做我想做的事情 - 这是mixin的多重继承(我说的组合/授权)我的VB5 / 6天 - 当我有一个工具来生成繁琐的重复委托代码时 - 它正在寻找一个C#等价物,我找到了LinFu)。
进一步编辑:澄清组合/授权和mixin的含义。
public class Person : NEOtherBase, IName, IAge
{
public Person()
{
}
public Person(string name, int age)
{
Name = name;
Age = age;
}
//Name "Mixin" - you'd need this code in any object that wanted to
//use the NameObject to implement IName
private NameObject _nameObj = new NameObject();
public string Name
{
get { return _nameObj.Name; }
set { _nameObj.Name = value; }
}
//--------------------
//Age "Mixin" you'd need this code in any object that wanted to
//use the AgeObject to implement IAge
private AgeObject _ageObj = new AgeObject();
public int Age
{
get { return _ageObj.Age; }
set { _ageObj.Age = value; }
}
//------------------
}
public interface IName
{
string Name { get; set; }
}
public class NameObject : IName
{
public NameObject()
{}
public NameObject(string name)
{
_name = name;
}
private string _name;
public string Name { get { return _name; } set { _name = value; } }
}
public interface IAge
{
int Age { get; set; }
}
public class AgeObject : IAge
{
public AgeObject()
{}
public AgeObject(int age)
{
_age = age;
}
private int _age;
public int Age { get { return _age; } set { _age = value; } }
}
想象一下具有更多属性的对象,在更多的“子类”中使用,你开始看到单调乏味。代码生成工具实际上只是很好 ......
所以,林富...... 下面的mixin示例很好,但我想要一个真正的Person class (如上所述) - LinFu-esque的做法是什么?或者我错过了重点?
编辑:我需要能够使用已经子类化的类来完成此任务。
DynamicObject dynamic = new DynamicObject();
IPerson person = null;
// This will return false
bool isPerson = dynamic.LooksLike<IPerson>();
// Implement IPerson
dynamic.MixWith(new HasAge(18));
dynamic.MixWith(new Nameable("Me"));
// Now that it’s implemented, this
// will be true
isPerson = dynamic.LooksLike<IPerson>();
if (isPerson)
person = dynamic.CreateDuck<IPerson>();
// This will return “Me”
string name = person.Name;
// This will return ‘18’
int age = person.Age;