コード例 #1
0
 public static T False <T>(
     T value,
     Func <T, bool> condition,
     Exception exception)
 {
     False(NotNull(condition)(value), NotNull(exception));
     return(value);
 }
コード例 #2
0
 public static T True <T>(
     T value,
     Func <T, bool> condition,
     string?paramName = null,
     string?message   = IsNotTrueMessage)
 {
     True(NotNull(condition)(value), paramName, message);
     return(value);
 }
コード例 #3
0
ファイル: NotNullFixture.cs プロジェクト: stjordanis/amaranth
        public void TestImplicitWrap()
        {
            Foo           foo     = new Foo();
            NotNull <Foo> notNull = foo;

            Assert.AreEqual(foo, notNull.Value);
        }
コード例 #4
0
ファイル: NotNullFixture.cs プロジェクト: stjordanis/amaranth
        public void TestGetValue()
        {
            Foo           foo     = new Foo();
            NotNull <Foo> notNull = new NotNull <Foo>(foo);

            Assert.AreEqual(foo, notNull.Value);
        }
コード例 #5
0
        public void ValueShouldThrowExceptionGivenNullScalar()
        {
            Scalar <object> scalar = new NotNull <object>(null);
            Action          action = () => scalar.Value();

            action.ShouldThrow <Exception>().WithMessage("NULL instead of valid scalar");
        }
コード例 #6
0
        public override void AfterDamage(NotNull <Action> action, NotNull <Hit> hit)
        {
            // let the base handle elements
            base.AfterDamage(action, hit);

            //### bob: handle sustains and a chance to resist?

            // handle the flags
            TryDrain(action, hit.Value.Attack, Stats.Strength, "You feel weak.");
            TryDrain(action, hit.Value.Attack, Stats.Agility, "You feel clumsy.");
            TryDrain(action, hit.Value.Attack, Stats.Stamina, "You feel tired.");
            TryDrain(action, hit.Value.Attack, Stats.Will, "Your conviction falters.");
            TryDrain(action, hit.Value.Attack, Stats.Intellect, "You feel stupid.");
            TryDrain(action, hit.Value.Attack, Stats.Charisma, "You feel ugly.");

            // drain experience
            if (hit.Value.Attack.Flags.Has("drain:experience"))
            {
                // chance to resist
                if (Stats.Will.ResistDrain())
                {
                    action.Value.Log(LogType.Resist, this, "{possessive} will sustain[s] {pronoun}.");
                }
                else
                {
                    // lower by 1% - 5%
                    float percent = Rng.Float(0.01f, 0.05f);

                    action.Value.Log(LogType.BadState, this, "{subject} feel[s] {possessive} life draining away.");
                    LoseExperience(action.Value, Experience.Current * percent);
                }
            }
        }
コード例 #7
0
        public void EqualityOperators()
        {
            const string     @string      = "Which is the bigger number, five or one?";
            const string     otherString  = "Our purpose died with the Mad King.";
            string           nullString   = null;
            NotNull <string> notNull      = @string;
            NotNull <string> otherNotNull = otherString;

            // ReSharper disable ExpressionIsAlwaysNull
            (notNull == @string).Should().BeTrue();
            (@string == notNull).Should().BeTrue();
            (notNull == otherString).Should().BeFalse();
            (otherString == notNull).Should().BeFalse();
            (notNull == otherNotNull).Should().BeFalse();
            (notNull == nullString).Should().BeFalse();
            (nullString == notNull).Should().BeFalse();

            (notNull != @string).Should().BeFalse();
            (@string != notNull).Should().BeFalse();
            (notNull != otherString).Should().BeTrue();
            (otherString != notNull).Should().BeTrue();
            (notNull != otherNotNull).Should().BeTrue();
            (notNull != nullString).Should().BeTrue();
            (nullString != notNull).Should().BeTrue();
            // ReSharper restore ExpressionIsAlwaysNull
        }
コード例 #8
0
ファイル: NotNullTests.cs プロジェクト: KonH/UnitySamples
    void Start()
    {
        // Without exceptions it doesn't make sense
        Assert.raiseExceptions = true;

        // Works as usual
        var validObj1 = new NotNull <SomeClass>(new SomeClass("str"));

        SomeMethod(validObj1);

        // Alternative syntax
        var validObj2 = new SomeClass("str").AsNotNull();

        SomeMethod(validObj2);

        // In this case we get exception when creating instance
        try {
            NotNull <SomeClass> invalidObj = new NotNull <SomeClass>(null);
            SomeMethod(invalidObj);
        } catch (Exception e) {
            Debug.LogError(e);
        }

        // In this case we get exception when getting value
        try {
            NotNull <SomeClass> invalidObj = default(NotNull <SomeClass>);
            SomeMethod(invalidObj);
        } catch (Exception e) {
            Debug.LogError(e);
        }
    }
コード例 #9
0
ファイル: NotNullTests.cs プロジェクト: Fyzxs/CactooSharp
        public void ShouldThrowExceptionForNullText()
        {
            Text   notNull = new NotNull(null);
            Action action  = () => notNull.String();

            action.ShouldThrowExactly <Exception>().WithMessage("NULL instead of a valid text");
        }
コード例 #10
0
ファイル: Equipment.cs プロジェクト: stjordanis/amaranth
        /// <summary>
        /// Gets the quantity of the given item that can be stacked with the current
        /// equipment.
        /// </summary>
        /// <param name="item">The Item being stacked.</param>
        /// <returns>The amount of the Item that can be stacked, or zero if the
        /// Item is not stackable.</returns>
        public int GetStackCount(NotNull <Item> item)
        {
            // only handle stackable items
            if (!CanStack(item))
            {
                return(0);
            }

            for (int i = 0; i < Count; i++)
            {
                if (mCategories[i] == item.Value.Type.Category)
                {
                    // not merging stacks, so can stack the whole thing
                    if ((mItems[i] == null) || !mItems[i].CanStack(item))
                    {
                        return(item.Value.Quantity);
                    }

                    //### bob: hackish, -1 = stack is full
                    if (mItems[i].Quantity == Item.MaxQuantity)
                    {
                        return(-1);
                    }

                    // can stack, so just make sure the stack doesn't get too big
                    return(Math.Min(Item.MaxQuantity - mItems[i].Quantity, item.Value.Quantity));
                }
            }

            throw new ArgumentException("Category not found.");
        }
コード例 #11
0
        public void EqualsWithDifferentInstances(string first, string second, bool expected)
        {
            var firstNotNull  = new NotNull <string>(first);
            var secondNotNull = new NotNull <string>(second);

            firstNotNull.Equals(secondNotNull).Should().Be(expected);
        }
コード例 #12
0
        private static void Process <T>
        (
            NotNull <IBlockingQueue <HierarchyElement <T> > > queue,
            NotNull <Func <T, CancellationToken, IEnumerable <T> > > action,
            CancellationToken cancellationToken,
            NotNull <SearchTaskOptions> options
        )
        {
            var actions = new Action[options.Value.MaxDegreeOfParallelism];

            for (var i = 0; i < actions.Length; i++)
            {
                actions[i] = async() =>
                {
                    try
                    {
                        await ExecuteTask
                        (
                            queue,
                            options.Value.DequeueWaitTimeout,
                            action,
                            cancellationToken
                        );
                    }
                    catch (OperationCanceledException)
                    {
                        // It's just cancelling, no errors.
                    }
                };
            }

            ParallelTask
            .StartNew(actions)
            .Wait(CancellationToken.None);
        }
コード例 #13
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="fileWriter"></param>
 /// <param name="optimizedContentLengthBeforeMakeStream">Не обязателен, но при его задании чтение Length не будет приводить к созданию стрима с предварительной подготовкой</param>
 public FileContentProvider(FileWriterDelegate fileWriter,
                            ContentLengthDelegate optimizedContentLengthBeforeMakeStream = null)
 {
     NotNull.CheckArgument(() => fileWriter);
     _fileWriter = fileWriter;
     _optimizedContentLengthBeforeMakeStream = optimizedContentLengthBeforeMakeStream;
 }
コード例 #14
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="streamWriter"></param>
 /// <param name="optimizedContentLengthBeforeMakeStream">Не обязателен, но при его задании чтение Length не будет приводить к созданию стрима с предварительной подготовкой</param>
 public ContentProviderToStreamWritable(StreamWriterDelegate streamWriter,
                                        ContentLengthDelegate optimizedContentLengthBeforeMakeStream = null)
 {
     NotNull.CheckArgument(() => streamWriter);
     _streamWriter = streamWriter;
     _optimizedContentLengthBeforeMakeStream = optimizedContentLengthBeforeMakeStream;
 }
コード例 #15
0
        public static async Task StartNew <T>
        (
            IEnumerable <T> initialItems,
            Func <T, CancellationToken, IEnumerable <T> > action,
            CancellationToken cancellationToken,
            SearchTaskOptions options = null
        )
        {
            var notNullAction       = Argument.IsNotNull(action, nameof(action));
            var notNullInitialItems = Argument.IsNotNull(initialItems, nameof(initialItems));

            var items = notNullInitialItems.Value.ToArray();

            if (items.Length == 0)
            {
                throw new ArgumentException(@"Initial items collection cannot be empty", nameof(initialItems));
            }

            var queueOptions = NotNull <SearchTaskOptions> .Create(options ?? new SearchTaskOptions());

            var queue = NotNull <IBlockingQueue <HierarchyElement <T> > > .Create
                        (
                new HierarchicalLimitedBlockingQueue <T>(items, queueOptions.Value.MaxQueueLength,
                                                         queueOptions.Value.MaxHierarchyDepth)
                        );

            await Task.Run
            (
                () => { Process(queue, notNullAction, cancellationToken, queueOptions); },
                cancellationToken
            );
        }
コード例 #16
0
ファイル: NotNullTest.cs プロジェクト: vladris/Maki.NET
        public void NotNullMakeOptionalMake()
        {
            var optional = NotNull.MakeOptional("Foo");

            Assert.IsTrue(optional.HasValue);
            Assert.AreEqual("Foo", optional.Get().Item);
        }
コード例 #17
0
ファイル: NotNullTests.cs プロジェクト: Fyzxs/CactooSharp
        public void ShouldReturnInputAsString()
        {
            Text text    = new TextOf("val");
            Text notNull = new NotNull(text);

            notNull.String().Should().Be("val");
        }
コード例 #18
0
 /// <summary>
 /// To be used with IfNull. This method is invoked in case the value checked by IsNull actually is not null.
 /// </summary>
 /// <param name="notnull">Internal use.</param>
 /// <param name="action">Action to be executed in case the value is null.</param>
 public static void Else <T>(this NotNull <T> notnull, Action <T> action)
 {
     if (notnull != null)
     {
         action.Invoke(notnull.Value);
     }
 }
コード例 #19
0
        public ArgumentBuilder AddArgument(string arg)
        {
            Argument.IsNotEmpty(arg, @"arg");

            _stringBuilder.AppendFormat(" {0}", EscapeString(NotNull.Wrap(arg)));

            return(this);
        }
コード例 #20
0
ファイル: PlayGameScreen.cs プロジェクト: stjordanis/amaranth
        public void Drop(NotNull <Item> item)
        {
            int quantity = PromptForItemQuantity(item, item.Value.Quantity, item.Value.Quantity);

            mGame.Hero.SetNextAction(new DropAction(mGame.Hero, item, quantity));

            ProcessGame();
        }
コード例 #21
0
ファイル: NotNullTest.cs プロジェクト: vladris/Maki.NET
        public void NotNullCastItemTest()
        {
            NotNull <string> notNull = "Foo";

            Action <string> action = (s) => Assert.AreEqual("Foo", s);

            action(notNull);
        }
コード例 #22
0
        public void NotEmptyStringConvertsToStringTest()
        {
            var expectedValue = new Version(1, 2, 3, 4);

            var notNullValue = NotNull.Wrap(expectedValue);

            Assert.AreEqual(expectedValue.ToString(), notNullValue.ToString());
        }
コード例 #23
0
 /// <summary>
 /// Creates a new BoltAction starting at the <see cref="Entity"/> and moving in the given <see cref="Direction"/>.
 /// </summary>
 public BoltAction(NotNull <Entity> entity, Direction direction)
     : this(entity, entity.Value.Position + direction.Offset)
 {
     if (direction == Direction.None)
     {
         throw new ArgumentException("Direction.None is not a valid direction.");
     }
 }
コード例 #24
0
ファイル: NotNullTests.cs プロジェクト: Fyzxs/CactooSharp
        public void ShouldThrowExceptionForNullTextValue()
        {
            Text   text    = new TextOf((string)null);
            Text   notNull = new NotNull(text);
            Action action  = () => notNull.String();

            action.ShouldThrowExactly <Exception>().WithMessage("NULL instead of a valid result string");
        }
コード例 #25
0
        public void ValueShouldThrowExceptionGivenValidValue()
        {
            object          actual   = new object();
            Scalar <object> scalar   = new NotNull <object>(actual);
            object          expected = scalar.Value();

            expected.Should().BeSameAs(actual);
        }
コード例 #26
0
        public static async Task StartNew(Action action, int parallelCount)
        {
            Argument.IsNotNull(action, nameof(action));
            Argument.IsInRange(parallelCount, nameof(parallelCount), 2, int.MaxValue);

            var actions = NotNull <IEnumerable <Action> > .Create(Enumerable.Repeat(action, parallelCount));

            await StartCore(actions);
        }
コード例 #27
0
ファイル: NotNullFixture.cs プロジェクト: stjordanis/amaranth
        public void TestImplicitUnwrap()
        {
            Foo           foo     = new Foo();
            NotNull <Foo> notNull = new NotNull <Foo>(foo);

            Foo unwrap = notNull;

            Assert.AreEqual(foo, unwrap);
        }
コード例 #28
0
		internal FinallyBlock(NotNull<Action> tryAction)
		{
			_tryFunc =
				() =>
				{
					tryAction.Value.Invoke();
					return true;
				};
		}
コード例 #29
0
ファイル: NotNullTest.cs プロジェクト: vladris/Maki.NET
        public void NotNullEqualsTest()
        {
            Assert.IsFalse(NotNull.Make(new T1()).Equals(NotNull.Make(new T1())));
            Assert.IsTrue(NotNull.Make("test").Equals(NotNull.Make("test")));

            Assert.IsTrue("test".Equals(NotNull.Make("test")));

            Assert.IsFalse(NotNull.Make(new T1()).Equals(null));
        }
コード例 #30
0
        public void NotNullTest()
        {
            var obj = new object();

            var notNullObj = NotNull <object> .Create(obj);

            Assert.IsNotNull(notNullObj);
            Assert.IsNotNull(notNullObj.Value);
        }
コード例 #31
0
ファイル: Tests.cs プロジェクト: blowin/NotNull
        public void ImplicitConvert()
        {
            var str = "Data";

            NotNull <string> notNull      = str.ToNotNull();
            string           notNullValue = notNull;

            Assert.AreEqual(str, notNullValue);
        }
コード例 #32
0
 public object this[NotNull] Type key]
 {
     get { return null; }
     set { throw new NotSupportedException(); }
 }
コード例 #33
0
 /// <summary>
 ///   Returns a value from the YafContext Global Instance Variables (Vars) collection.
 /// </summary>
 /// <param name = "varName"></param>
 /// <returns>Value if it's found, null if it doesn't exist.</returns>
 public object this[NotNull] string varName]
コード例 #34
0
 /// <summary>
 ///   The this.
 /// </summary>
 /// <param name = "key">
 ///   The key.
 /// </param>
 public object this[NotNull] string key]
コード例 #35
0
 public string this[NotNull] string key]
コード例 #36
0
 /// <summary>
 ///   Gets panel session state.
 /// </summary>
 /// <param name = "panelID">panelID</param>
 /// <returns></returns>
 public CollapsiblePanelState this[NotNull] string panelID]
コード例 #37
0
ファイル: Element.cs プロジェクト: modulexcite/0install-win
 public Command this[NotNull] string name]
コード例 #38
0
 /// <summary>
 /// The this.
 /// </summary>
 /// <param name="key">
 /// The key.
 /// </param>
 public object this[NotNull] object key]
コード例 #39
0
ファイル: CommandContext.cs プロジェクト: permyakov/janus
 public object this[NotNull] string name]
コード例 #40
0
 public IEnumerable<Edge> this[NotNull] Vertex vertex]
 {
     get { return _vertices[vertex]; }
 }
コード例 #41
0
ファイル: Record.cs プロジェクト: mvbalaw/EtlGate
 public string this[NotNull] string name]