开发者

How to get property type passed to T in C#?

开发者 https://www.devze.com 2023-02-09 11:12 出处:网络
Ok, Here is what I\'m doing, I have a class called Settings Settings has a list of properties: I\'m trying to make it as dynamic as possible.

Ok,

Here is what I'm doing, I have a class called Settings

Settings has a list of properties:

I'm trying to make it as dynamic as possible.

So I can just copy and paste each property and just change its name and it will grab the new setting by the name

Example..

public string Url
{ get { return Get<string>(MethodBase.GetCurrentMethod()); } }
public int Port
{ get { return Get<int>(MethodBase.GetCurrentMethod()); } }

private T Get<T>(MethodBase method)
{
  // Code that pulls setting from the property name
}

Question is,开发者_如何学Python how can I pass the properties type to Get, that way I don't have to specify the data type twice..

I know this is wrong but sort of like

Get<MethodBase.GetCurrentMethod().GetType()>(MethodBase.GetCurrentMethod());


It is not possible to infer a return type; you cannot do this using generics.

If Get doesn't use typeof(T), you can change it to return dynamic instead of using generics. The caller can then implicitly cast the result in its return statement.

There may be a performance penalty, though.


You can't do something like

Get<MethodThatReturnsAType()>

because the generic type is set at compile time. I'm sort of wondering what the advantage you're getting here is. You could have the Get simply return object and manage the cast in the property.

What behaviour do you expect if the setting is missing for example, or defined but the wrong type?

0

精彩评论

暂无评论...
验证码 换一张
取 消