Programing

변수에 코드 할당

crosscheck 2020. 7. 9. 08:10
반응형

변수에 코드 할당


다음과 같이 변수를 만들고 코드 줄을 지정할 수 있습니까?

ButtonClicked = (MessageBox.Show("Hello, World!"));

... 변수를 사용하면 코드 줄이 실행됩니다.


다음 Action과 같이 지정할 수 있습니다 .

var ButtonClicked = new Action(() => MessageBox.Show("hi"));

그런 다음 전화하십시오.

ButtonClicked();

완전성을 위해 (다양한 의견과 관련하여) ...

Erik이 말했듯이 여러 줄의 코드를 실행할 수 있습니다.

var ButtonClicked = new Action(() =>
{
    MessageBox.Show("hi");

    MessageBox.Show("something else");  // something more useful than another popup ;)
});

Tim이 말했듯이 Action키워드를 생략 할 수 있습니다

Action ButtonClicked = () => MessageBox.Show("hi");

Action ButtonClicked = () =>
{
    // multiple lines of code
};

빈 괄호와 관련하여 KRyan의 의견을 처리하기 위해 조치에 보낼 매개 변수 목록 (이 경우 none)을 나타 냅니다.

예를 들어, 표시 할 메시지를 지정하려는 경우 "message"를 매개 변수로 추가 할 수 있습니다 ( 단일 문자열 매개 변수를 지정하기 위해 변경 한 Action 것에 유의하십시오 ) .Action<string>

Action<string> ButtonClicked = (message) => MessageBox.Show(message);

ButtonClicked("hello world!");

귀하의 경우에는을 사용하려고합니다 delegate.

델리게이트의 작동 방식과 개념을 이해하여 더 쉬운 양식을 얻는 방법을 살펴 보겠습니다.

// Create a normal function
void OnButtonClick()
{
    MessageBox.Show("Hello World!");
}
// Now we create a delegate called ButtonClick
delegate void ButtonClick();

아시다시피, 델리게이트는 일반적인 함수의 형태를 취하지 만 인수는 없습니다 (다른 방법과 마찬가지로 많은 양의 인수를 취할 수는 있지만 단순성을 위해 그렇지 않습니다).

이제 우리가 가진 것을 사용합시다. 다른 변수를 정의하는 것처럼 대리자를 정의합니다.

ButtonClick ButtonClicked = new ButtonClick(OnButtonClick);

기본적으로 ButtonClicked라는 새 변수를 만들었습니다.이 변수에는 대리자 인 ButtonClick 형식이 있으며 사용시 OnButtonClick () 메서드에서 메서드를 실행합니다.
그것을 사용하기 위해 우리는 단순히 전화 :ButtonClicked();

따라서 전체 코드는 다음과 같습니다.

delegate void ButtonClick();

void OnButtonClick()
{
    MessageBox.Show("Hello World!");
}

void Foo()
{
    ButtonClick ButtonClicked = new ButtonClick(OnButtonClick);
    ButtonClicked(); // Execute the function.
}  

From here, we can move to lambda expressions and see how they could be useful in your situation:
There are many delegates already defined by .NET libraries, with some like Action, which do not accept any parameter and does no return a value. It is defined as public delegate void Action();
You can always use it to your needs instead of the need of defining a new delegate every time. In the previous context for example, you could had just written

Action ButtonClicked = new Action(OnButtonClick);
ButtonClicked();

which would had done the same.
Now that you saw different ways of how to use delegates, let's use our first lambda expression. Lambda expressions are anonymous functions; so, they are normal functions but without a name. They are of those forms:

x => DoSomethingWithX(x);
(x) => DoSomethingWithX(x);
(x,y) => DoSometingWithXY(x,y);
() => Console.WriteLine("I do not have parameters!");

In our case, we do not have any parameters so we will use the last expression. We can use this just as the OnButtonClick function, but we get the advantage of not having a named function. We can instead do something like this:

Action ButtonClicked = new Action( () => MessageBox.Show("Hello World!") );

or even easier,

Action ButtonClicked = () => MessageBox.Show("Hello World!");

then simply call ButtonClicked(); Of course you can also have multi-lines of code, but I do not want to confuse you more. It would look like this though:

Action ButtonClicked = () => 
{
    MessageBox.Show("Hello World!");
};
ButtonClicked();

You could also play around, for example, you can execute a function like this:

new Action(() => MessageBox.Show("Hello World!"))();

Sorry for the long post, hope it was not too confusing :)

EDIT: I forgot to mention that an alternate form which, even though not often used, could make lambda expressions easier to understand:

new Action(delegate() {
    Console.WriteLine("I am parameterless");
})();

Also, using generics:

// Defines a delegate that has one parameter of type string. You could pass as many parameters as you want.
new Action<string>(delegate(string x) {
    Console.WriteLine(x);
})("I am a string parameter!");

In turn you could use lambda expressions, but you do not need (but might in some cases) to define the type of the parameter, for example, the code above could simply be written as:

new Action<string>(x => {
    Console.WriteLine(x);
})("I am a string parameter!");

or:

new Action<string>(x => Console.WriteLine(x))("I am a string parameter!");

EDIT2:
Action<string> is a representation of public void delegate Action(string obj);
Action<string,string> is a representation of public void delegate Action(string obj, string obj2);
In general, Action<T> is a representation of public void delegate Action<T>(T obj);

EDIT3: I know the post has been here for a while, but I think this is really cool to not mention: You can do this, which is mostly related to your question:

dynamic aFunction = (Func<string, DialogResult>)MessageBox.Show;
aFunction("Hello, world!");

or simply:

Func<string, DialogResult> aFunction = MessageBox.Show;
aFunction("Hello, world!");

The Lazy class is specifically designed to represent a value that won't be computed until you ask for it. You construct it by providing a method that defines how it should be constructed, but it will handle executing that method no more than once (even in the face of multiple threads requesting the value) and simply returning the already constructed value for any additional requests:

var foo = new Lazy<DialogResult>(()=>MessageBox.Show("Hello, World!"));

var result = foo.Value;

The way I'm reading your question, this is in the context of GUI controls?

If this is in WPF, take a look at the "right" way to handle commands from controls: http://msdn.microsoft.com/en-us/library/ms752308(v=vs.110).aspx

...but that can be a pain and overkill. For a simpler general case, you might be looking for an event handler, like:

myButton.Click += (o, e) => MessageBox.Show("Hello, World!");

That event handler can be handled a variety of ways. The above example uses an anonymous function, but you could also do:

Action<object, RoutedEventArgs> sayHello = (o, e) => MessageBox.Show("Hello, World");
myButton.Click += new RoutedEventHandler(sayHello);

...just like you were asking, with a function (or here, "Action", since it returns void) assigned as a variable.


You can assign C# code to a variable, compiling it at runtime and run the code:

  • Write your code:

    // Assign C# code to the code variable.
    string code = @"
    using System;
    
    namespace First
    {
        public class Program
        {
            public static void Main()
            {
                " +
                "Console.WriteLine(\"Hello, world!\");"
                + @"
            }
        }
    }
    ";
    
  • Create the provider and parameters of the compiler:

    CSharpCodeProvider provider = new CSharpCodeProvider();
    CompilerParameters parameters = new CompilerParameters();
    
  • Define parameters of the compiler:

    // Reference to System.Drawing library
    parameters.ReferencedAssemblies.Add("System.Drawing.dll");
    // True - memory generation, false - external file generation
    parameters.GenerateInMemory = true;
    // True - exe file generation, false - dll file generation
    parameters.GenerateExecutable = true;
    
  • Compile assembly:

    CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
    
  • Check errors:

    if (results.Errors.HasErrors)
    {
            StringBuilder sb = new StringBuilder();
    
            foreach (CompilerError error in results.Errors)
            {
                    sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
            }
    
            throw new InvalidOperationException(sb.ToString());
    }
    
  • Get assembly, type and the Main method:

    Assembly assembly = results.CompiledAssembly;
    Type program = assembly.GetType("First.Program");
    MethodInfo main = program.GetMethod("Main");
    
  • Run it:

    main.Invoke(null, null);
    

Reference:

http://www.codeproject.com/Tips/715891/Compiling-Csharp-Code-at-Runtime

참고URL : https://stackoverflow.com/questions/23119687/assigning-code-to-a-variable

반응형