Skip to main content
 首页 » 编程设计

c#之访问类的重对象成员的正确方法

2024年02月06日12haluo1

我有这样一个类:

class BuildingFloor 
{ 
    // The list of building rooms; 
    // Room is "heavy" object with many-many fields 
    List< Room > m_rooms; 
 
    // The list of all apertures on the floor 
    List< Aperture > m_apertures; 
    ... 
    List< Room > Rooms 
    { 
        get { return m_rooms; } 
    } 
 
    List< Aperture > Doors 
    { 
        get{ return GetAperturesOfType( 2 ); } 
    } 
    public List< Aperture > Exits 
    { 
        get{ return GetAperturesOfType( 3 ); } 
    } 
    ... 
    List< Aperture > GetAperturesOfType( int type ) 
    { 
        var apertures = new List<ApertureWrapper>(); 
        foreach ( var aper in m_apertures ) 
        { 
            if ( ( aper.Type == type ) ) 
            { 
                apertures.Add( aper ); 
            } 
        } 
        return apertures; 
    } 
} 

我的问题是:
1) 威尔m_rooms当客户端代码访问 Rooms 时被复制属性(property);
2)多少次List<>对象将在 Doors 上构建属性调用。

那么,我可以在此代码中更改哪些内容以使其更快?
我需要在代码中大量使用这些属性,例如
foreach( var door in m_floor.Doors) { ... }
注意:Profiler 显示 Exits属性(property)花费了大量的时间。证明:

请您参考如下方法:

Will m_rooms be copied when client code will access Rooms property

是的。但是m_rooms的值只是一个引用 - 它不是 List<Room>对象本身。您可能想阅读我关于 reference types and value types 的文章.

How many times List<> object will be constructed on the Doors property call.

  1. 正在调用 GetAperturesOfType一次,构造一个新的 List<ApertureWrapper> .

您的属性(property)将更简单地实现为:

return m_apertures.Where(x => x.Type == 2).ToList(); 

(听起来您可能也想要一个 ApertureType 枚举...)

另请注意,如果您只是需要遍历门,您可以使用:

return m_apertures.Where(x => x.Type == 2); 

并避免创建 List<>根本。请注意,这在其他方面会有不同的语义......

Profiler says Doors property spent significant amount of time.

好吧,您需要查看实际有多少个孔,有多少个门,以及您调用 Doors 的频率。属性(property)。仅从您向我们展示的内容,我们无法真正判断总体上什么是重要的。性能工作通常是上下文相关的。

编辑:现在我们已经看到了调用代码,如果您使用局部变量会更好:

var exits = m_building.CurrentFloor.Exits; 
for (int i = 0; i < exits.Count; i++) 
{ 
    // Use exits[i] within here 
    // Set exitId to i + 1 if you find the exit. 
    // (Or ideally, change everything to be 0-based...) 
} 

否则,您将为循环的每次迭代创建一个新列表。