VB.NET - 如何将对象分配给对象实例(内部更好的描述)

时间:2008-11-07 08:43:06

标签: vb.net

我有一个对象实例,我在访问实例化对象时访问它。我有一个获取这些对象集合的方法,我希望将第一个对象分配给实例化对象。

这是一些代码

Dim Books As New BookCollection(True)
Books.ListByThemeFeatured(ThemeID, 1) ' Fills the collection

If Books.Count > 0 Then
   Me = Books(0) ' Should set the first item to the current object
End If

这可能吗?

编辑:我指的是实例化的类。在这种情况下,它是BookEntity类。这个方法可以使用以下代码调用

 Dim Book As New BookEntity
 Book.FeaturedBook() ' Should fill the book entity with a featured book

4 个答案:

答案 0 :(得分:0)

你做不到。您正在寻找的是静态(在VB中共享)方法:

Dim Book as BookEntity
Book = BookEntity.FeaturedBook()

答案 1 :(得分:0)

似乎不可能,因为您尝试替换没有句柄的对象实例。一种选择可能是将当前Book实例的所有成员替换为Books(0)的值,如:

Me.ConstructMeFrom(Books(0))

ConstructMeFrom取代所有图书的字段:

Sub ConstructMeFrom(Book newBook)
    Me.Title = newBook.Title
    Me.PageCount = newBook.PageCount
    'etc
End Sub

或者您可以设计一些方法来修改保存实例的句柄的值。对于例如您可以使用委托将实例本身替换为另一个实例。我不熟悉vb语法,但这里是如何在c#:

中完成的
public class Book
{
    public delegate void Replacer(Book book);

    public void ReplaceMe(Replacer replacer, Book newBook)
    {
        replacer(newBook);
    }

    public int PageCount;
}

static void Main(string[] args)
{
    Book b1 = new Book() { PageCount = 3 };
    Book b2 = new Book() { PageCount = 5 };
    b1.ReplaceMe(book => b1 = book, b2);
    Console.WriteLine(b1.PageCount); // Output is 5.
}

<强>更新

带有更新示例的C#示例:

FeaturedBook(Replacer replacer)
{
    Book featuredBook = FindTheFeaturedBookFromSomeList();
    replacer(featuredBook);
}

现在这样做:

BookEntity Book;
Book = BookEntity.FeaturedBook(delegate(BookEntity b) { Book = b; });

答案 2 :(得分:0)

使用子

public sub FeaturedBooks() 
    dim FB as Book = GetFeaturedBook() 
    CopyToMe(FB) 
end sub

private shared sub CopyToMe(Abook as book)
    Me.Bookname = aBook.BookName
     etc
end sub

或拥有共享功能,以便您编写:

Dim Book as BookEntity = BookEntity.FeaturedBook()


Class BookEntity

Public shared function FeaturedBook() as BookEntity
    Dim NewBook as BookEntity
    Get the featured book into here...

    return NewBook
end function

end class

答案 3 :(得分:0)

我很抱歉,但是对于那段代码“闻起来很糟糕”...为什么你需要替换当前的BookEntity对象?您的代码看起来正在做一些应该超出BookEntity范围的事情。

我认为你应该有一个像BookDisplayer这样的类,它有一个CurrentBook属性来处理显示新书所需的逻辑。当然,假设这是你想要完成的事情。

修改

看起来像下面的代码示例:

Book.FeaturedBook() ' Should fill the book entity with a featured book

应该是这样的,FeaturedBook类的BookCollection逻辑代替:

Book = Books.GetFeaturedBook()
' NOW perform display logic