1

Please tell me about how to get a field name from an instance variable.

public class MainClass
{
    public void output()
    {
        Action valAction = new TestClass().testAction;

        //I want to output string 'testAction' from valAction variable here
        Debug.WriteLine(valAction.????);
    }
}

public class TestClass
{
    public Action testAction = () => { };
}
0

2 Answers 2

1

Sounds like you have an XY Problem.

Fact is, it is not possible to do literally what you want. Once you have copied the value that your field testAction holds into a different variable (the local variable valAction), the original field is no longer involved.

Consider the simpler example:

class A
{
    int i = 17;

    void M()
    {
        int j = i;
    }
}

Would you expect to be able to somehow glean "i" from the variable j? I hope not. The variable j holds a 32-bit integer value. It doesn't care where that value came from, nor should it.

Similarly valAction doesn't hold any information about where the value it received came from. It holds only the value itself.

If you can explain the broader problem you're trying to address here, you may be able to get a solution. But there is none to the question you've asked here. You are literally asking for the impossible.

Sign up to request clarification or add additional context in comments.

2 Comments

When I substitute named Function for a variable of valAction, I am as follows. {Method = {Void namedFunction()}} However, I am as follows when I substitute Lambda. I do not know which Lambda you show in this. {Method = {Void <.ctor>b__1_0()}} Therefore I want to know member variable name 'testAction'.
@kyounoii: "I want to know member variable name 'testAction'" -- you can't. That's what I'm saying. You are confusing the delegate instance itself, from which you could extract the method target name, with the variable that stores the delegate instance. When the delegate instance is assigned to any other variable, it in no way remains related to the variable that it was assigned from.
0

Replace

Debug.WriteLine(valAction.????);

with

Debug.WriteLine((Type.GetType(a.ToString()).GetMember("testAction"))[0]);

2 Comments

What is a in the above? How does this, in any way, address the question that was asked? If you have to specify the string literal "testAction", how is this better than just calling Debug.WriteLine("testAction");?
I want to come out without using literal 'testAction'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.