Выполните итерации через параметры метода в целях проверки

Я сделал это при помощи pywin32. Это не особенно приятное впечатление, так как нет действительно никакой абстракции; это похоже на использование VBA, но с синтаксисом Python. Вы не можете полагаться на docstrings, таким образом, Вы захотите иметь MSDN удобная ссылка Excel (, http://msdn.microsoft.com/en-us/library/aa220733.aspx - то, что я использовал, если я помню правильно. Необходимо быть в состоянии найти документы Excel 2007, если Вы роете вокруг немного.).

См. здесь для простого примера.

from win32com.client import Dispatch

xlApp = Dispatch("Excel.Application")
xlApp.Visible = 1
xlApp.Workbooks.Add()
xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!'
xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!'
xlApp.ActiveWorkbook.Close(SaveChanges=0) # see note 1
xlApp.Quit()
xlApp.Visible = 0 # see note 2
del xlApp

Удачи!

8
задан bluish 29 November 2018 в 14:55
поделиться

7 ответов

Well, not unless you count:

public void Foo(string x, object y, Stream z, int a)
{
    CheckNotNull(x, y, z);
    ...
}

public static void CheckNotNull(params object[] values)
{
    foreach (object x in values)
    {
        if (x == null)
        {
            throw new ArgumentNullException();
        }
    }
}

To avoid the array creation hit, you could have a number of overloads for different numbers of arguments:

public static void CheckNotNull(object x, object y)
{
    if (x == null || y == null)
    {
        throw new ArgumentNullException();
    }
}

// etc

An alternative would be to use attributes to declare that parameters shouldn't be null, and get PostSharp to generate the appropriate checks:

public void Foo([NotNull] string x, [NotNull] object y, 
                [NotNull] Stream z, int a)
{
    // PostSharp would inject the code here.
}

Admittedly I'd probably want PostSharp to convert it into Code Contracts calls, but I don't know how well the two play together. Maybe one day we'll be able to write the Spec#-like:

public void Foo(string! x, object! y, Stream! z, int a)
{
    // Compiler would generate Code Contracts calls here
}

... but not in the near future :)

15
ответ дан 5 December 2019 в 09:26
поделиться

You can define method parameter with a params keyword. This will make it possible to pass a variable-length number of parameters to your method. You can then iterate over them and check for null references or whatever you want with it.

public void MyMethod(params object[] parameters) {
     foreach (var p in parameters) {
         ...
     }
}

// method call:
this.MyMethod("foo", "bar", 123, null, new MyClass());

In my opinion however, it's not a good way of doing things. You will have to manually control the type of your parameters, their position in the input array and you won't be able to use intellisense for them in Visual Studio.

2
ответ дан 5 December 2019 в 09:26
поделиться

Некоторое время назад у меня был такой же вопрос, но я хотел сделать это для целей регистрации. Я так и не нашел хорошего решения, но нашел эту ссылку, касающуюся использования подхода, основанного на АОП, для записи и выхода метода ведения журнала. Суть в том, чтобы использовать фреймворк, который может читать ваш класс и вводить код во время выполнения, чтобы делать то, что вы пытаетесь сделать. Звучит непросто.

Как мне перехватить вызов метода в C #?

1
ответ дан 5 December 2019 в 09:26
поделиться

It is possible to iterate over the parameters that have been declared for a method (via reflection), but I see no way to retrieve the value of those parameters for a specific method call ...

Perhaps you could use Postsharp, and create an aspect in where you perform this check. Then, at compile time, Postsharp can 'weave' the aspect (inject additional code) at every method that you 've written ...

0
ответ дан 5 December 2019 в 09:26
поделиться

You can look into The Validation Application Block which can be treated as an example of automated validation and The Unity Application Block (in particular its interception feature) in respect to intercepting calls and inspecting parameters.

0
ответ дан 5 December 2019 в 09:26
поделиться

You could quite probably automate parameter checking with an AOP library such as PostSharp.

0
ответ дан 5 December 2019 в 09:26
поделиться

После предоставления тривиального примера метода с использованием ключевого слова params , RaYell говорит:

Однако, на мой взгляд, это не очень хорошо способ делать вещи. Тебе придется вручную контролировать тип вашего параметры, их положение в входной массив, и вы не сможете используйте для них intellisense в Visual Studio.

I would certainly agree that declaring a method that takes two strings, one int, an object that can be null, and another MyClass object using params is a bad idea. However, there are (in my opinion) perfectly valid and appropriate applications of the params keyword, namely when the parameters are all of the same type. For example:

public T Max<T>(T x, T y) where T : IComparable<T> {
    return x.CompareTo(y) > 0 ? x : y;
}

public T Max<T>(params T[] values) where T : IComparable<T> {
    T maxValue = values[0];

    for (int i = 1; i < values.Length; i++) {
        maxValue = Max<T>(maxValue, values[i]);
    }

    return maxValue;
}
0
ответ дан 5 December 2019 в 09:26
поделиться
Другие вопросы по тегам:

Похожие вопросы: