如何从方法返回对对象的const引用? [英] How may I return a const reference to an object from a method?

查看:105
本文介绍了如何从方法返回对对象的const引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public Item getItem(ulong itemId)
{
    Item item = items[itemId]
    return item;
}

现在的问题是: getItem 必须能够检索项目拥有的信息;

Now the problem is: the callee of getItem must be able to retrieve information that item holds; but not modify it.

抱歉,但是我知道C ++比C#好……我怕为了使它变得小巧,我必须回到C ++上来。自己清楚我要实现的目标...因此,在这种情况下,这就是我在C ++中要做的事情:

Sorry, but I know C++ better than C#... I'm afraid I must fall back to C++ for a teeny tiny while just to make myself clear what I'm trying to achieve... So this is what I'd do in C++ in this situation:

const Item& getItem(unsigned long itemId)
{
    const Item& item = items[itemId];
    return item;
}

很好-现在有人叫 getItem 可以在上调用吸气剂,但不能在setter上调用。

Very well - now whoever called getItem may call getters on item, but not setters.

我需要在C#...有可能吗?

I need to achieve a similar result in C#... is it possible?

推荐答案

您可以使用接口仅显示getter,同时仍支持实现该类的setter接口。只要您返回 interface ,任何使用者都将仅限于该接口定义的getter。

You can use interfaces to surface only getters while still supporting setters in the class that implements the interface. As long as you return the interface, any consumer will be restricted to only the getters that interface defines.

public interface IItem {
    string SomeProperty { get; }
}

public class Item : IItem {
    public string SomeProperty { get; set; }
}

public class ItemHandler {
    private Item _item = new Item();

    public IItem getItem() {
        _item.SomeProperty = "A Value";
        return _item;
    }
}

class Program {
    static void Main(string[] args) {
        var itemHandler = new ItemHandler();
        var item = itemHandler.getItem();

        // You can read the property
        Console.WriteLine(item.SomeProperty);

        // You can't write to the property
        //item.SomeProperty = "A New Value";
    }
}

这篇关于如何从方法返回对对象的const引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆