public Item getItem(ulong itemId)
{
Item item = items[itemId]
return item;
}
现在的问题是:被调用者getItem
必须能够检索以下信息item
持有;但不修改它。
抱歉,但我比 C# 更了解 C++...恐怕我必须回到 C++ 一小会儿,只是为了让自己清楚我要实现的目标...所以这就是我要做的在 C++ 中这种情况:
const Item& getItem(unsigned long itemId)
{
const Item& item = items[itemId];
return item;
}
很好 - 现在无论谁打电话getItem
可能会调用吸气剂item
,但不是设置者。
我需要在 C# 中实现类似的结果...可能吗?
您可以使用接口仅显示 getter,同时仍然支持实现该接口的类中的 setter。只要你归还界面,任何消费者都将仅限于接口定义的 getter。
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";
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)