2013-07-04 48 views
1

我同时获得使用LINQ的DataContext动态设定值功能属性的C#中的参数

我想下面的代码

公共类DBContextNew从数据库数据列表面临的问题:DataContext的 {

public static string StoreProcedureName = ""; 

    [Function(Name = StoreProcedureName, IsComposable = false)] 
    public ISingleResult<T> getCustomerAll() 
    { 

     IExecuteResult objResult = 
      this.ExecuteMethodCall(this, (MethodInfo)(MethodInfo.GetCurrentMethod())); 

     ISingleResult<T> objresults = 
      (ISingleResult<T>)objResult.ReturnValue; 
     return objresults; 
    } 


} 

但我得到错误

[功能(名称= StoreProcedureName,IsComposable =假)]作为属性参数

必须是常量表达式,属性参数类型

我的typeof运算 表达或数组创建表达式想在运行时将值传递给Name属性。

可能吗?

请帮忙。

+1

这是不可能的,属性参数无法在运行时传递 – wudzik

+1

尽管深度反射是可能的。但是你必须知道,运行时反射会导致性能问题,所以你必须尽一切努力才能生存下来。当你在项目启动或某个单身官员工作上做某事时,反思是很好的。 – Maris

+0

忘记将动态数据传递给属性,告诉我们您将尝试存档的内容,并且我们将尝试帮助您解决问题,而无需使用属性。 – Maris

回答

0

的问题是:

public static string StoreProcedureName = ""; 

你需要使它成为一个常数。

public const string StoreProcedureName = ""; 

编译器在错误消息中告诉你(它必须是一个常量表达式)。

+0

谢谢,但我想在运行时为StoreProcedureName赋值,所以它不适用于我。 –

+1

@NileshNikumbh - 我不认为你可以在运行时传递它们。我遇到过类似的问题, –

0

不幸的是,您不能为属性声明提供动态值(如变量的内容)。

但是你可以在运行时更改属性的值:

public class TestAttribute : Attribute 
{ public string Bar { get; set; } } 

public class TestClass 
{ 
    [Test] 
    public string Foo() 
    { return string.Empty; } 
} 

然后改变这个值:

var method = typeof(TestClass).GetMethod("Foo"); 
var attribute = method.GetCustomAttribute(typeof(TestAttribute)) as TestAttribute; 
attribute.Bar = "Hello"; 

请记住,属性在您的类的所有实例共享。

+0

您必须重新解释这会导致多线程问题。 – Maris

0

使用城堡动态代理而不是简单属性。因为使用属性来强制执行它会强制您在运行时使用反射来更改属性参数中的某些内容。这样,就像user1908061一样会引起2个问题:

1)性能问题。在运行时调用存储过程对于应用程序的性能非常“重量级”。2)多线程问题。让我们想象一下,2个线程调用此码为10,间隔蜱

var method = typeof(TestClass).GetMethod("Foo"); 
var attribute = method.GetCustomAttribute(typeof(TestAttribute)) as TestAttribute; 
attribute.Bar = "Hello"; 

线程1将改变Bar参数的时属性为“Hello”在这一次的线程2将访问相同的代码,并且将改变Bar参数去一些其他的价值,这将导致问题。让我们在时间轴上看看它:

0 ticks - Thread1 started to work, accessed the property of TestAttribute and made the Bar param = "Hello" 
20 ticks - Thread2 started to work, accessed the property of TestAttribute and made the Bar param = "SomeOtherValue" 
40 ticks - You are expecting that you will call function with `Bar`=="Hello", but it's getting called with the `Bar`=="SomeOtherValue" 
60 ticks - Thread2 getting called with `Bar`=="SomeOtherValue" 

所以你的Thread1会得到错误的结果。

所以我会建议使用CastleDynamicProxy做你想做的。有了它,你可以在方法之前运行一些代码,并替换方法的结果,并且你可以在方法之后运行一些代码。这种方式将在运行时工作。

此外还有一项技术 - PostSharp将以相同的方式执行相同操作,但有一点会以另一种方式进行。这个将在编译时工作。

+0

显然你可以在属性设置器中添加一个锁来避免线程问题。 – user1908061

+0

Yeap。这将解决部分问题。但让我们假设你有1000000个线程正在运行并试图访问这个方法,但他们不能这样做,因为'Bar'被锁定了。这会带来更多问题。这个过程将变得更加难以控制。 – Maris