我正在尝试为以下任务创建一个委托(作为测试):
Public Overridable ReadOnly Property PropertyName() As String
我的直觉尝试是这样声明代表:
Public Delegate Function Test() As String
并像这样实例化:
Dim t As Test = AddressOf e.PropertyName
但这会引发错误:
方法'公共可重写只读属性PropertyName()为
字符串'没有签名
与委托'代表兼容
函数Test()作为String'。
因此,因为我正在处理某个物业,所以尝试了以下方法:
Public Delegate Property Test() As String
但这会引发编译器错误。
所以问题是,如何为财产委派代表?
看到这个链接:
http://peisker.net/dotnet/propertydelegates.htm
参考方案
使用AddressOf来解决问题-如果在编译时知道prop-name,则可以(至少在C#中)使用anon方法/ lambda:
Test t = delegate { return e.PropertyName; }; // C# 2.0
Test t = () => e.PropertyName; // C# 3.0
我不是VB专家,但是反射器声称这与以下内容相同:
Dim t As Test = Function
Return e.PropertyName
End Function
那样有用吗?
原始答案:
您可以使用Delegate.CreateDelegate
为属性创建委托;它可以对任何类型的实例打开,对于单个实例是固定的-可以用于getter或setter;我会用C#举例说明...
using System;
using System.Reflection;
class Foo
{
public string Bar { get; set; }
}
class Program
{
static void Main()
{
PropertyInfo prop = typeof(Foo).GetProperty("Bar");
Foo foo = new Foo();
// create an open "getter" delegate
Func<Foo, string> getForAnyFoo = (Func<Foo, string>)
Delegate.CreateDelegate(typeof(Func<Foo, string>), null,
prop.GetGetMethod());
Func<string> getForFixedFoo = (Func<string>)
Delegate.CreateDelegate(typeof(Func<string>), foo,
prop.GetGetMethod());
Action<Foo,string> setForAnyFoo = (Action<Foo,string>)
Delegate.CreateDelegate(typeof(Action<Foo, string>), null,
prop.GetSetMethod());
Action<string> setForFixedFoo = (Action<string>)
Delegate.CreateDelegate(typeof(Action<string>), foo,
prop.GetSetMethod());
setForAnyFoo(foo, "abc");
Console.WriteLine(getForAnyFoo(foo));
setForFixedFoo("def");
Console.WriteLine(getForFixedFoo());
}
}
如何在会话状态下添加List <string> - c#有没有办法在会话中添加列表?或以其他方式在另一个页面中传递List的值? 参考方案 List<string> ast = new List<string>(); ast.Add("asdas!"); Session["stringList"] = ast; List<string> …
为什么要使用Func <string>而不是string? - c#为什么要使用Func<string>而不是string?我的问题特别是关于this回购。有问题的行是22: private static Func<string> getToken = () => Environment.GetEnvironmentVariable("GitHubToken", Enviro…
与哪些运算符>>兼容 - java我这里没有什么代码int b=3; b=b >> 1; System.out.println(b); 它可以完美工作,但是当我将变量b更改为byte,short,float,double时,它包含错误,但是对于变量int和long来说,它可以完美工作,为什么它不能与其他变量一起工作? 参考方案 位移位运算符(例如>>)与任何整数类型兼…
>> Python中的运算符 - python>>运算符做什么?例如,以下操作10 >> 1 = 5有什么作用? 参考方案 它是右移运算符,将所有位“右移”一次。二进制10是1010移到右边变成0101这是5
如何为.NET Core 3.0 Worker服务设置事件日志 - c#我正在使用带有.NET Core 3.0预览版的新Worker Service应用程序模板,并尝试使用AddEventLog方法添加事件日志记录。但是,我无法通过Windows中的事件查看器看到任何日志。我有一个非常简单的Worker应用程序设置,并配置了Program.cs文件中的日志记录,如下所示:public static IHostBuilder C…