gpt4 book ai didi

c# - 在运行时创建属性并传递值

转载 作者:太空宇宙 更新时间:2023-11-03 12:45:04 25 4
gpt4 key购买 nike

我找到了创建运行时函数的示例。

public static MethodInfo CreateFunction(string function)
{
string code = @"
using System;

namespace UserFunctions
{
public class BinaryFunction
{
public static double Function(double x, double y)
{
return func_xy;
}
}
}
";

string finalCode = code.Replace("func_xy", function);

CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerResults results = provider.CompileAssemblyFromSource(new CompilerParameters(), finalCode);

Type binaryFunction = results.CompiledAssembly.GetType("UserFunctions.BinaryFunction");
return binaryFunction.GetMethod("Function");
}

主要内容:

static void Main(string[] args)
{
MethodInfo function = CreateFunction("x + 2 * y");
object result = function.Invoke(null, new object[] { 2, 3 });
Console.WriteLine(result);
}

主要问题是如何在运行时创建属性并在 Main 中将值传递给它?

public static PropertyInfo CreateProperty()
{
string code=@"
private string name;

public string Name {
get{
return this.name;
}
set{
this.name=value;
}
}
";
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerResults results = provider.CompileAssemblyFromSource(new CompilerParameters(),code);
///
}

最佳答案

同样的道理?

public static Type CreateProperty(string value)
{
string code = @"
namespace UserFunctions
{
public class MyProperty
{
private string name = my_value

public string Name {
get{
return this.name;
}
set{
this.name=value;
}
}
}
}
";
code = code.Replace("my_value", '"' + value + '"');
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerResults results = provider.CompileAssemblyFromSource(new CompilerParameters(), code);
Type myProperty = results.CompiledAssembly.GetType("UserFunctions.MyProperty");
return myProperty;
}

static void Main()
{

Type propertyType = CreateProperty("this is a value");
var property = propertyType.GetProperty("Name");
var instance = Activator.CreateInstance(propertyType);

Console.WriteLine(property.GetValue(instance, null));

property.SetValue(instance, "MyNewValue", null);
Console.WriteLine(property.GetValue(instance, null));
}

关于c# - 在运行时创建属性并传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37616943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com