What are some examples of dynamic / generic / other methods for generating return type based on caller type?

In the context of C #,. Net 4 ...

Given a data source object that supplies vertices at an index from a doubling array, where the vertex contains ten paired elements with elements Px, Py, Pz, Nx, Ny, Nz, S, T, U, V. and the base array contains all or any a subset of vertex elements based on the properties of the step, offset, and count of the data source. A data source can be simplified as:

  public class DataSource
  {
    private double[] data;
    private int offset, stride, count;

    public double[] ElementAt(int index)
    {
      double[] result = new double[count];
      var relativeIndex =  index * stride + offset;
      Array.Copy(data, relativeIndex, result, 0, count);
      return result;
    }
    .
    .
    .
  }

double [], PointNf, N - (Point1f... Point10f). Point , , . Point4f 3 [i + 0], [i + 1], [i + 2], 0.

, DataSource GetPoint1f (int index), GetPoint2f ( int) . , .. ...

, ...

Point3f point = SomeDataSource.ElementAt[index];

... //?... /... , ?... ?

+3
2

, ...

Point3f point = SomeDataSource.ElementAt[index];

... //?

:

// I’m guessing it’s a struct, but can be a class too
public struct Point3f
{
    // ...

    public static implicit operator Point3f(double[] array)
    {
        // Just for demonstration: in real code,
        // please check length and nullity of array first!
        return new Point3f(array[0], array[1], array[2]);
    }

    // You can declare one that goes the other way too!
    public static implicit operator double[](Point3f point)
    {
        return new double[] { point.Px, point.Py, point.Pz };
    }
}
+5

PointNf, index?

, factory - , , , . factory :

public T GetElementAt<T>(int index) where T : new() {
    Type type = typeof(T);
    T result = new T()
    if (type==typeof(Point3f)) {
        result.X = data[index];
        result.Y = data[index+1];
        result.Z = data[index+2];
    }
    else if (type==typeof(Point2f) {
        result.X = data[index];
        result.Y = data[index+1];
    }
    return result;
}

NB: , X, Y, Z T, .

T . , , PointNf, . PointNf (IPointDataProvider) void PopulateData(double[] data, int index), , factory

public T GetElementAt<T>(int index) where T : IPointDataProvider, new() {
    T result = new T()
    result.PopulateData(data, index)
    return result;
}

, .

class Point2f : IPointDataProvider {
    double X, Y;

    void IPointDataProvider.PopulateData(double[] data, int index) {
        X = data[0];
        Y = data[1];
    }
}
+1

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


All Articles