Tag: indexed properties

Moq是一个索引属性,并使用返回/回调中的索引值

我想moq一个具有索引的属性,我希望能够在回调中使用索引值,就像在moq方法的回调中使用方法参数一样。 可能最容易用一个例子来certificate: public interface IToMoq { int Add(int x, int y); int this[int x] { get; set; } } Action DoSet = (int x, int y) => { Console.WriteLine(“setting this[{0}] = {1}”, x, y); throw new Exception(“Do I ever get called?”); }; var mock = new Mock(MockBehavior.Strict); //This works perfectly mock.Setup(m => m.Add(It.IsAny(), It.IsAny())) .Returns((a, […]

在C#中命名为索引属性?

一些语言 – 比如Delphi – 有一种非常方便的方法来创建索引器:不仅是整个类,甚至单个属性都可以被编入索引,例如: type TMyClass = class(TObject) protected function GetMyProp(index : integer) : string; procedure SetMyProp(index : integer; value : string); public property MyProp[index : integer] : string read GetMyProp write SetMyProp; end; 这可以很容易地使用: var c : TMyClass; begin c = TMyClass.Create; c.MyProp[5] := ‘Ala ma kota’; c.Free; end; 有没有办法轻松地在C#中实现相同的效果?

是否可以命名索引器属性?

假设我在类中有一个数组或任何其他集合,以及一个返回它的属性,如下所示: public class Foo { public IList Bars{get;set;} } 现在,我可以这样写: public Bar Bar[int index] { get { //usual null and length check on Bars omitted for calarity return Bars[index]; } }

轻松创建支持C#索引的属性

在C#中,我发现索引属性非常有用。 例如: var myObj = new MyClass(); myObj[42] = “hello”; Console.WriteLine(myObj[42]); 但据我所知,没有语法糖来支持自己支持索引的字段(如果我错了请纠正我)。 例如: var myObj = new MyClass(); myObj.field[42] = “hello”; Console.WriteLine(myObj.field[42]); 我需要这个的原因是我已经在我的类上使用索引属性,但我有GetNumX() , GetX()和SetX()函数如下: public int NumTargetSlots { get { return _Maker.NumRefs; } } public ReferenceTarget GetTarget(int n) { return ReferenceTarget.Create(_Maker.GetReference(n)); } public void SetTarget(int n, ReferenceTarget rt) { _Maker.ReplaceReference(n, rt._Target, true); } 你可能会看到将这些暴露为一个可索引的字段属性会更有意义。 […]