我有这样的工作(实验室)做: ...有关事件的信息必须写在一些文件中,这些文件必须通过附加到此类属性来确定。 Wgat感觉是在这个属性?它必须做什么?
所有实验都是“编写通用类列表时,有机会在调用某些类方法时生成事件。有关事件的信息必须写在某些文件中,必须通过附加到此类属性来确定。
我不明白在本实验室属性中使用的原因,请帮帮我。
这里我编写了列表
的示例通用类以下是两个文件:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lab7
{
public class MyListClass<T>: IEnumerable<T>
{
public delegate void MyDelegate();
public event MyDelegate AddEvent;
public event MyDelegate RemEvent;
List<T> list;
public T this[int index]
{
get { return list[index]; }
set { list[index] = value; }
}
public void Add(T item)
{
list.Add(item);
if (AddEvent != null)
AddEvent();
}
public void Remove(T item)
{
list.Remove(item);
if (RemEvent != null)
RemEvent();
}
public void RemoveAt(int index)
{
list.RemoveAt(index);
if (RemEvent != null)
RemEvent();
}
public MyListClass()
{
list = new List<T>();
}
public MyListClass(List<T> list)
{
this.list = list;
}
public IEnumerator<T> GetEnumerator()
{
return list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return list.GetEnumerator();
}
#region Events
/*static void AddHandler()
{
Console.WriteLine("Объект добавлен в коллекцию");
}
static void RemoveHandler()
{
Console.WriteLine("Объект удалён из коллекции");
}*/
#endregion
}
}
这是主要的课程:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lab7
{
class Program
{
static void Main(string[] args)
{
MyListClass<int> lst = new MyListClass<int>();
lst.AddEvent +=new MyListClass<int>.MyDelegate(AddHandler);
lst.RemEvent+=new MyListClass<int>.MyDelegate(RemoveHandler);
lst.Add(2542);
lst.Add(785);
lst.RemoveAt(1);
}
static void AddHandler()
{
Console.WriteLine("Объект добавлен в коллекцию");
}
static void RemoveHandler()
{
Console.WriteLine("Объект удалён из коллекции коллекцию");
}
}
}
抱歉我的英语不好。我不是说要为我做所有的实验,只给我一些想法,并举例说明如何写这个)
答案 0 :(得分:1)
这个问题很难理解,但我认为它希望你用一个属性来装饰你的类或方法,该属性指向存储某种事件数据的文件。
所以它看起来像这样:
class SomeClass
{
[MyEventInfoAttribute(EventFile = "c:\\blah\\events.foo")]
void SomeMethod()
{
}
}
所以你需要定义一个属性:
public class MyEventInfoAttribute : Attribute
{
public property string EventFile { get; set; }
}
如何存储活动信息并实施活动取决于您。
您的代码必须使用反射来发现方法的属性。
例如:
class SomeClass
{
[MyEventInfoAttribute(EventFile = "c:\\blah\\events.foo")]
void SomeMethod()
{
Type type = typeof(SomeClass);
MethodInfo method = type.GetMethod("SomeMethod");
object[] atts = method.GetCustomAttributes();
if (atts.Length > 0)
{
if (atts[0] is MyEventInfoAttribute)
{
string fileName = ((MyEventInfoAttribute)atts[0]).EventFile;
... now open the file, read the event info, and use it ...
}
}
}
}
这是一个简化的示例,可让您了解要进入的方向。