Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

c# - How to use local variable as a type? Compiler says "it is a variable but is used like a type"

At run-time, I don't know what type of variable v1 is. For this reason, I wrote many if else statements:

if (v1 is ShellProperty<int?>)
{
    v2 = (v1 as ShellProperty<int?>).Value;
}
else if (v1 is ShellProperty<uint?>)
{
    v2 = (v1 as ShellProperty<uint?>).Value;
}
else if (v1 is ShellProperty<string>)
{
    v2 = (v1 as ShellProperty<string>).Value;
}
else if (v1 is ShellProperty<object>)
{
    v2 = (v1 as ShellProperty<object>).Value;
}    

The only difference is in ShellProperty<AnyType>.

So instead of writing this with a lot of if else statements, I decided to use reflection to get the property type at run-time:

 Type t1 = v1.GetType().GetProperty("Value").PropertyType;
 dynamic v2 = (v1 as ShellProperty<t1>).Value;

This code gets the PropertyType of v1 and assigns it to the local variable t1, but after that, my compiler says that:

t1 is a variable but is used like a type

So it does not allow me to write t1 inside ShellProperty<>.

Please tell me how to solve this problem and how to get more compact code than what I have. Do I need to create a new class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You were very close, you were just missing a call to MakeGenericType.

I believe your code would look like the following:

Type t1 = v1.GetType().GetProperty("Value").PropertyType;
var shellPropertyType = typeof(ShellProperty<>);
var specificShellPropertyType = shellPropertyType.MakeGenericType(t1);
dynamic v2 = specificShellPropertyType.GetProperty("Value").GetValue(v1, null);

Edit: As @PetSerAl pointed out I added some layers of indirection that were unnecessary. Sorry OP, you probably want a one liner like:

dynamic v2 = v1.GetType().GetProperty("Value").GetValue(v1, null);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...