在 C#、.Net 4 的上下文中...
给定一个数据源对象,该对象按 double 组的索引提供顶点,其中顶点包含十个 double ,成员为 Px、Py、Pz、Nx、Ny、Nz、S、T、U、V 和后备数组包含基于数据源的步幅、偏移量和计数属性的所有或顶点成员的任何子集。数据源可以简化为:
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 类型的消费者不关心源的步幅,并且源为大于其步幅的成员提供零。例如来自步长 3 的源的 Point4f 将填充数据[i + 0]、数据[i + 1]、数据[i + 2]、0。
显然,DataSource 可以公开方法 GetPoint1f(int index)、GetPoint2f(int index) 等。给定一组固定的返回类型、元素大小等,这些类型的解决方案可能是最好的。但是...
如果像...这样的语法有什么可能的解决方案
Point3f point = SomeDataSource.ElementAt[index];
...或类似要求/要求/期望?...优点/缺点?...不该做什么的示例?...苛刻的语言?
最佳答案
What are possible solutions if a syntax like…
Point3f point = SomeDataSource.ElementAt[index];
...or similar was requested/required/desired ?
这是用户定义的隐式转换的主要候选对象:
// 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 };
}
}
关于c# - 根据调用者的类型生成返回类型的动态/通用/其他方法有哪些示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3622815/