0

我有一个班级学生。我想将 Student 'objStu' 类的对象存储在剪贴板上。

Class Student
{
    string stuID;
    string Name;
    string email;
}

在main方法中我写了一段代码:

Clipboard.SetDataObject(objStu,false);

当我尝试如下检索对象时:

Student anotherStu = Clipboard.GetDataObject() as Student;

它返回空值。请指导我如何实现它。

4

1 回答 1

2

使学生类为Serializable

[Serializable]
public class Student
{
    public string stuID { get; set; }
    public string Name { get; set; }
    public string email { get; set; }
    public void CopyToClipboard()
    {

        DataFormats.Format format =
             DataFormats.GetFormat(typeof(Student).FullName);
        //now copy to clipboard
        IDataObject dataObj = new DataObject();
        dataObj.SetData(format.Name, false, this);
        Clipboard.SetDataObject(dataObj, false);

    }

然后你尝试:

Student objStu = new Student();
objStu.Name = "test";
objStu.CopyToClipboard();
Clipboard.SetDataObject(objStu, false);
Student anotherStu = GetFromClipboard();

下面是 GetFromClipboard 方法

protected static Student GetFromClipboard()
{
    Student student = null;
    IDataObject dataObj = Clipboard.GetDataObject();
    string format = typeof(Student).FullName;

    if (dataObj.GetDataPresent(format))
    {
        student = dataObj.GetData(format) as Student;
    }
    return student;
}

检查此链接以获取更多信息

于 2012-06-14T08:27:15.950 回答