我有一个类,其字段始终返回相同的字符串:
public class A
{
// cool C# 6.0 way to implement a getter-only property.
public string MyString => "This is a cool string!"
}
有没有办法使用反射(或者我可能会遗漏的其他方式)返回MyString而不必实例化A的新实例?签名无法更改,因此不能选择静态签名。
答案 0 :(得分:3)
不,它是一个实例属性,如果它是一个静态属性,那么你可以,但是你需要实例化该对象以获得实际的返回值,因为你需要为GetValue方法提供一个实例来进行反射,并且为静态属性传递null
答案 1 :(得分:3)
不,由于问题中的属性是实例(不是public class MultiThreadedExample : IDisposable
{
private Thread _thread;
private ManualResetEvent _terminatingEvent = new ManualResetEvent(false);
private ManualResetEvent _runningEvent = new ManualResetEvent(false);
private ManualResetEvent _threadStartedEvent = new ManualResetEvent(false);
public MultiThreadedExample()
{
_thread = new Thread(MyThreadMethod);
_thread.Start();
_threadStartedEvent.WaitOne();
}
private void MyThreadMethod()
{
_threadStartedEvent.Set();
var events = new WaitHandle[] { _terminatingEvent, _runningEvent };
while (WaitHandle.WaitAny(events) != 0) // <- WaitAny returns index within the array of the event that was Set.
{
try
{
// do work......
}
finally
{
// reset the event. so it can be triggered again.
_runningEvent.Reset();
}
}
}
public bool TryStartWork()
{
// .Set() will return if the event was set.
return _runningEvent.Set();
}
public bool IsRunning
{
get { return _runningEvent.WaitOne(0); }
}
public void Dispose()
{
// break the whileloop
_terminatingEvent.Set();
// wait for the thread to terminate.
_thread.Join();
}
}
),因此您必须提供实例。要通过 Reflection 获取属性:
static
您可能希望将该属性声明为A myA = new A();
...
String value = myA.GetType().GetProperty("MyString").GetValue(myA) as String;
,在这种情况下,您不必拥有任何实例。注意,Reflection并不想要一个实例:
static