我是初学者。在C#3.0中练习。要求是“我必须以这样的方式设计模型,它应该遍历实现特定接口的所有类
(在本例中为IExpressWords
)并执行实现的方法(void ExpressWords()
)“
我收集了List中的所有类并进行了迭代。
namespace InterfaceExample
{
public interface IExpressWords
{
void ExpressWords();
}
class GroupOne:IExpressWords
{
string[] str = { "Good", "Better", "Best" };
public void ExpressWords()
{
foreach (string s in str)
{
Console.WriteLine(s);
}
}
}
class GroupTwo:IExpressWords
{
string[] str = { "one", "two", "three" };
public void ExpressWords()
{
foreach (string s in str)
{
Console.WriteLine(s);
}
}
}
class Test
{
static void Main()
{
List<IExpressWords> word = new List<IExpressWords>();
word.Add(new GroupOne());
word.Add(new GroupTwo());
foreach (IExpressWords Exp in word)
{
Exp.ExpressWords();
}
Console.ReadKey(true);
}
}
}
问题:
(如果我在描述中不那么清楚,请告诉我)。
感谢大家常年的回应。
答案 0 :(得分:1)
1)这是strategy pattern
2)由于IExpressWords接口只包含一个方法,因此它实际上是一个方法的包装器,这是委托的用途。等效的委托类型是Action。所以你的代码将成为:
var groupOne = () =>
{
foreach(string s in new[] { "Good", "Better", "Best" })
{
Console.WriteLine(s);
}
}
var groupTwo = () =>
{
foreach(string s in new[] { "one", "two", "three" })
{
Console.WriteLine(s);
}
}
List<Action> acts = new List<action> { groupOne, groupTwo };
foreach(var a in acts)
{
a();
}
3)要查找在当前程序集中实现接口的所有类型,您可以执行以下操作:
a = Assembly.GetExecutingAssembly();
var implementingTypes = a.GetTypes().Where(t => typeof(IExpressWords).IsAssignableTo(t));
答案 1 :(得分:0)
如果您愿意,可以使用Action类来使用委托来实现此目的
class Test
{
static void Main()
{
List<Action> word = new List<Action>();
word.Add(new GroupOne().ExpressWords());
word.Add(new GroupTwo().ExpressWords());
foreach (Action del in word)
{
del();
}
Console.ReadKey(true);
}
}
如果要使用Delegates,则必须声明委托类型
delegate void SomeMethod();
class Test
{
static void Main()
{
List<SomeMethod> word = new List<SomeMethod>();
word.Add(new GroupOne().ExpressWords());
word.Add(new GroupTwo().ExpressWords());
foreach (SomeMethod del in word)
{
del();
}
Console.ReadKey(true);
}
}
答案 2 :(得分:0)
关于反思案例,这是一个小例子:
static void WreakHavoc<T>(Action<T> havok)
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var implementing = from assembly in assemblies
from type in assembly.GetTypes()
let interfaceType = typeof(T)
where interfaceType.IsAssignableFrom(type)
select type;
foreach(var type in implementing)
{
var ctor = type.GetConstructor(Type.EmptyTypes);
if (ctor == null) continue;
var instance = (T)ctor.Invoke(new object[0]);
havok(instance);
}
}
static void Main()
{
WreakHavoc<System.Collections.IEnumerable>((e) =>
{
foreach (var o in e)
{
Console.WriteLine(o);
}
});
}