Operator as and generic classes

女生的网名这么多〃 提交于 2019-12-09 02:07:15

问题


I'm writing .NET On-the-Fly compiler for CLR scripting and want execution method make generic acceptable:

object Execute()
{
  return type.InvokeMember(..);
}

T Execute<T>()
{
  return Execute() as T; /* doesn't work:
  The type parameter 'T' cannot be used with the 'as' operator because
  it does not have a class type constraint nor a 'class' constraint */

  // also neither typeof(T) not T.GetType(), so on are possible

  return (T) Execute(); // ok
}

But I think operator as will be very useful: if result type isn't T method will return null, instead of an exception! Is it possible to do?


回答1:


You need to add

where T : class

to your method declaration, e.g.

T Execute<T>()  where T : class
{

By the way, as a suggestion, that generic wrapper doesn't really add much value. The caller can write:

MyClass c = whatever.Execute() as MyClass;

Or if they want to throw on fail:

MyClass c = (MyClass)whatever.Execute();

The generic wrapper method looks like this:

MyClass c = whatever.Execute<MyClass>();

All three versions have to specify exactly the same three entities, just in different orders, so none are any simpler or any more convenient, and yet the generic version hides what is happening, whereas the "raw" versions each make it clear whether there will be a throw or a null.

(This may be irrelevant to you if your example is simplified from your actual code).




回答2:


You cannot use the as operator with a generic type with no restriction. Since the as operator uses null to represent that it was not of the type, you cannot use it on value types. If you want to use obj as T, T will have to be a reference type.

T Execute<T>() where T : class
{
  return Execute() as T;
}



回答3:


This small piece of code is an exception safe substitution for the as-keyword:

return Execute() is T value ? value : default(T)

It uses the pattern matching feature introduced with C# 7. Use it, if you don't want to restrict the generic parameter to a reference type




回答4:


It seems like you are just adding a wrapper method for casting to the type the user wants, thus only adding overhead to the execution. For the user, writing

int result = Execute<int>();

isn't much different from

int result = (int)Execute();

You can use the out modifier to write the result into a variable in the caller's scope, and return a boolean flag to tell whether it succeeded:

bool Execute<T>(out T result) where T : class
{
    result = Execute() as T;
    return result != null;
}



回答5:


Is there a chance that Execute() might return a value type? If so, then you need Earwicker's method for class types, and another generic method for value types. Might look like this:

Nullable<T> ExecuteForValueType<T> where T : struct

The logic inside that method would say

object rawResult = Execute();

Then, you'd have to get the type of rawResult and see if it can be assigned to T:

Nullable<T> finalReturnValue = null;

Type theType = rawResult.GetType();
Type tType = typeof(T);

if(tType.IsAssignableFrom(theType))
{
    finalReturnValue = tType;     
}

return finalReturnValue;

Finally, make your original Execute message figure out which T is has (class or struct type), and call the appropriate implementation.

Note: This is from rough memory. I did this about a year ago and probably don't remember every detail. Still, I hope pointing you in the general direction helps.



来源:https://stackoverflow.com/questions/693463/operator-as-and-generic-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!