Type function <type> ()

Today I saw something similar in some graphics libraries, and it seems that it can be very useful.

In the demo, I saw that it looked like this:

Texture2D texture = Content.Load<Texture2D>("Textures//Road");
Effect shader = Content.Load<Effect>("Effects//Road");

I assume this is a function that returns any type defined in brackets <>, and performs a different action for different types.

I want to implement something similar to myself, how is it used?

+3
source share
4 answers

The method Loadcan be used to download a large number of different types of content, including things such as images and sounds. Therefore, it can return instances of different types (for example, yours Texture2dand Effect).

, . -, , Object, .NET XNA .

public object Load(string path) { /*...*/}

:

Texture2D texture = (Texture2D)Content.Load("Textures//Road");

- . , . :

public T Load<T>(string path)
{
    return (T)Load(path);
}

, ( , T) .

, , - ,

public Texture2d LoadTexture2d(string path)
{
    return (Texture2d)Load(path);
}    
public Effect LoadEffect(string path)
{
    return (Effect)Load(path);
}
//500 more versions omitted for brevity
+4

generics.

:

public T ConvertValue<T>(Object value)
{
    return (T)Convert.ChangeType(value, typeof(T));
}

:

Generics ( #)

+9

Generics Type Independent programming. Generics , . , .

:

public class Stack<T>
{
   T[] m_Items; 
   public void Push(T item)
   {...}
   public T Pop()
   {...}
}
Stack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
int number = stack.Pop();

, ,

http://msdn.microsoft.com/en-us/library/ms379564%28v=vs.80%29.aspx#csharp_generics_topica

http://msdn.microsoft.com/en-us/library/512aeb7t%28VS.80%29.aspx

+2

The Load method really determines what it should return, and so is already defined for you. Inside the load method, contentLoader decides how to load it. There are several XNA examples for loading your own data. If you create something like: .world-file. You can create your own AssetLoader, which determines how to load your own data.

0
source

Source: https://habr.com/ru/post/1786740/


All Articles